es6.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. var finalVertexCode;
  216. this._loadVertexShaderAsync(vertexSource)
  217. .then(function (vertexCode) {
  218. return _this._processIncludesAsync(vertexCode);
  219. })
  220. .then(function (vertexCodeWithIncludes) {
  221. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  222. return _this._loadFragmentShaderAsync(fragmentSource);
  223. })
  224. .then(function (fragmentCode) {
  225. return _this._processIncludesAsync(fragmentCode);
  226. })
  227. .then(function (fragmentCodeWithIncludes) {
  228. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  229. if (baseName) {
  230. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  231. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  232. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  233. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  234. }
  235. else {
  236. _this._vertexSourceCode = finalVertexCode;
  237. _this._fragmentSourceCode = migratedFragmentCode;
  238. }
  239. _this._prepareEffect();
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @ignore */
  348. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. return Promise.resolve(vertexCode);
  354. }
  355. }
  356. // Base64 encoded ?
  357. if (vertex.substr(0, 7) === "base64:") {
  358. var vertexBinary = window.atob(vertex.substr(7));
  359. return Promise.resolve(vertexBinary);
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. return Promise.resolve(fragmentCode);
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (fragment.substr(0, 7) === "base64:") {
  386. var fragmentBinary = window.atob(fragment.substr(7));
  387. return Promise.resolve(fragmentBinary);
  388. }
  389. // Is in local store ?
  390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  391. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  392. }
  393. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  394. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  395. }
  396. var fragmentShaderUrl;
  397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  398. fragmentShaderUrl = fragment;
  399. }
  400. else {
  401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  402. }
  403. // Fragment shader
  404. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  405. };
  406. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  407. // Rebuild shaders source code
  408. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  409. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  410. vertexCode = prefix + vertexCode;
  411. fragmentCode = prefix + fragmentCode;
  412. // Number lines of shaders source code
  413. var i = 2;
  414. var regex = /\n/gm;
  415. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. i = 2;
  417. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  418. // Dump shaders name and formatted source code
  419. if (this.name.vertexElement) {
  420. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  421. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  422. }
  423. else if (this.name.vertex) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  426. }
  427. else {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  430. }
  431. };
  432. ;
  433. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  434. var preparedSourceCode = this._processPrecision(sourceCode);
  435. if (this._engine.webGLVersion == 1) {
  436. return preparedSourceCode;
  437. }
  438. // Already converted
  439. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  440. return preparedSourceCode.replace("#version 300 es", "");
  441. }
  442. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  443. // Remove extensions
  444. // #extension GL_OES_standard_derivatives : enable
  445. // #extension GL_EXT_shader_texture_lod : enable
  446. // #extension GL_EXT_frag_depth : enable
  447. // #extension GL_EXT_draw_buffers : require
  448. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  449. var result = preparedSourceCode.replace(regex, "");
  450. // Migrate to GLSL v300
  451. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  452. result = result.replace(/attribute[ \t]/g, "in ");
  453. result = result.replace(/[ \t]attribute/g, " in");
  454. if (isFragment) {
  455. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  456. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  457. result = result.replace(/texture2D\s*\(/g, "texture(");
  458. result = result.replace(/textureCube\s*\(/g, "texture(");
  459. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  460. result = result.replace(/gl_FragColor/g, "glFragColor");
  461. result = result.replace(/gl_FragData/g, "glFragData");
  462. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  463. }
  464. return result;
  465. };
  466. Effect.prototype._processIncludesAsync = function (sourceCode) {
  467. var _this = this;
  468. return new Promise(function (resolve, reject) {
  469. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  470. var match = regex.exec(sourceCode);
  471. var returnValue = sourceCode;
  472. while (match != null) {
  473. var includeFile = match[1];
  474. // Uniform declaration
  475. if (includeFile.indexOf("__decl__") !== -1) {
  476. includeFile = includeFile.replace(/__decl__/, "");
  477. if (_this._engine.supportsUniformBuffers) {
  478. includeFile = includeFile.replace(/Vertex/, "Ubo");
  479. includeFile = includeFile.replace(/Fragment/, "Ubo");
  480. }
  481. includeFile = includeFile + "Declaration";
  482. }
  483. if (Effect.IncludesShadersStore[includeFile]) {
  484. // Substitution
  485. var includeContent = Effect.IncludesShadersStore[includeFile];
  486. if (match[2]) {
  487. var splits = match[3].split(",");
  488. for (var index = 0; index < splits.length; index += 2) {
  489. var source = new RegExp(splits[index], "g");
  490. var dest = splits[index + 1];
  491. includeContent = includeContent.replace(source, dest);
  492. }
  493. }
  494. if (match[4]) {
  495. var indexString = match[5];
  496. if (indexString.indexOf("..") !== -1) {
  497. var indexSplits = indexString.split("..");
  498. var minIndex = parseInt(indexSplits[0]);
  499. var maxIndex = parseInt(indexSplits[1]);
  500. var sourceIncludeContent = includeContent.slice(0);
  501. includeContent = "";
  502. if (isNaN(maxIndex)) {
  503. maxIndex = _this._indexParameters[indexSplits[1]];
  504. }
  505. for (var i = minIndex; i < maxIndex; i++) {
  506. if (!_this._engine.supportsUniformBuffers) {
  507. // Ubo replacement
  508. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  509. return p1 + "{X}";
  510. });
  511. }
  512. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  513. }
  514. }
  515. else {
  516. if (!_this._engine.supportsUniformBuffers) {
  517. // Ubo replacement
  518. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  519. return p1 + "{X}";
  520. });
  521. }
  522. includeContent = includeContent.replace(/\{X\}/g, indexString);
  523. }
  524. }
  525. // Replace
  526. returnValue = returnValue.replace(match[0], includeContent);
  527. }
  528. else {
  529. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  530. _this._engine._loadFileAsync(includeShaderUrl)
  531. .then(function (fileContent) {
  532. Effect.IncludesShadersStore[includeFile] = fileContent;
  533. return _this._processIncludesAsync(returnValue);
  534. })
  535. .then(function (returnValue) {
  536. resolve(returnValue);
  537. });
  538. return;
  539. }
  540. match = regex.exec(sourceCode);
  541. }
  542. resolve(returnValue);
  543. });
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else {
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets an array of textures on the engine to be used in the shader.
  714. * @param channel Name of the variable.
  715. * @param textures Textures to set.
  716. */
  717. Effect.prototype.setTextureArray = function (channel, textures) {
  718. if (this._samplers.indexOf(channel + "Ex") === -1) {
  719. var initialPos = this._samplers.indexOf(channel);
  720. for (var index = 1; index < textures.length; index++) {
  721. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  722. }
  723. }
  724. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  725. };
  726. /**
  727. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  728. * @param channel Name of the sampler variable.
  729. * @param postProcess Post process to get the input texture from.
  730. */
  731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  733. };
  734. /** @ignore */
  735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  736. var cache = this._valueCache[uniformName];
  737. var flag = matrix.updateFlag;
  738. if (cache !== undefined && cache === flag) {
  739. return false;
  740. }
  741. this._valueCache[uniformName] = flag;
  742. return true;
  743. };
  744. /** @ignore */
  745. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  746. var cache = this._valueCache[uniformName];
  747. if (!cache) {
  748. cache = [x, y];
  749. this._valueCache[uniformName] = cache;
  750. return true;
  751. }
  752. var changed = false;
  753. if (cache[0] !== x) {
  754. cache[0] = x;
  755. changed = true;
  756. }
  757. if (cache[1] !== y) {
  758. cache[1] = y;
  759. changed = true;
  760. }
  761. return changed;
  762. };
  763. /** @ignore */
  764. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  765. var cache = this._valueCache[uniformName];
  766. if (!cache) {
  767. cache = [x, y, z];
  768. this._valueCache[uniformName] = cache;
  769. return true;
  770. }
  771. var changed = false;
  772. if (cache[0] !== x) {
  773. cache[0] = x;
  774. changed = true;
  775. }
  776. if (cache[1] !== y) {
  777. cache[1] = y;
  778. changed = true;
  779. }
  780. if (cache[2] !== z) {
  781. cache[2] = z;
  782. changed = true;
  783. }
  784. return changed;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y, z, w];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. if (cache[2] !== z) {
  804. cache[2] = z;
  805. changed = true;
  806. }
  807. if (cache[3] !== w) {
  808. cache[3] = w;
  809. changed = true;
  810. }
  811. return changed;
  812. };
  813. /**
  814. * Binds a buffer to a uniform.
  815. * @param buffer Buffer to bind.
  816. * @param name Name of the uniform variable to bind to.
  817. */
  818. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  819. var bufferName = this._uniformBuffersNames[name];
  820. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  821. return;
  822. }
  823. Effect._baseCache[bufferName] = buffer;
  824. this._engine.bindUniformBufferBase(buffer, bufferName);
  825. };
  826. /**
  827. * Binds block to a uniform.
  828. * @param blockName Name of the block to bind.
  829. * @param index Index to bind.
  830. */
  831. Effect.prototype.bindUniformBlock = function (blockName, index) {
  832. this._engine.bindUniformBlock(this._program, blockName, index);
  833. };
  834. /**
  835. * Sets an interger value on a uniform variable.
  836. * @param uniformName Name of the variable.
  837. * @param value Value to be set.
  838. * @returns this effect.
  839. */
  840. Effect.prototype.setInt = function (uniformName, value) {
  841. var cache = this._valueCache[uniformName];
  842. if (cache !== undefined && cache === value)
  843. return this;
  844. this._valueCache[uniformName] = value;
  845. this._engine.setInt(this.getUniform(uniformName), value);
  846. return this;
  847. };
  848. /**
  849. * Sets an int array on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param array array to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setIntArray = function (uniformName, array) {
  855. this._valueCache[uniformName] = null;
  856. this._engine.setIntArray(this.getUniform(uniformName), array);
  857. return this;
  858. };
  859. /**
  860. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  861. * @param uniformName Name of the variable.
  862. * @param array array to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setIntArray2 = function (uniformName, array) {
  866. this._valueCache[uniformName] = null;
  867. this._engine.setIntArray2(this.getUniform(uniformName), array);
  868. return this;
  869. };
  870. /**
  871. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  872. * @param uniformName Name of the variable.
  873. * @param array array to be set.
  874. * @returns this effect.
  875. */
  876. Effect.prototype.setIntArray3 = function (uniformName, array) {
  877. this._valueCache[uniformName] = null;
  878. this._engine.setIntArray3(this.getUniform(uniformName), array);
  879. return this;
  880. };
  881. /**
  882. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  883. * @param uniformName Name of the variable.
  884. * @param array array to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setIntArray4 = function (uniformName, array) {
  888. this._valueCache[uniformName] = null;
  889. this._engine.setIntArray4(this.getUniform(uniformName), array);
  890. return this;
  891. };
  892. /**
  893. * Sets an float array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setFloatArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets matrices on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param matrices matrices to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setMatrices = function (uniformName, matrices) {
  987. if (!matrices) {
  988. return this;
  989. }
  990. this._valueCache[uniformName] = null;
  991. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  992. return this;
  993. };
  994. /**
  995. * Sets matrix on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrix matrix to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1001. if (this._cacheMatrix(uniformName, matrix)) {
  1002. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1003. }
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1008. * @param uniformName Name of the variable.
  1009. * @param matrix matrix to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1019. * @param uniformName Name of the variable.
  1020. * @param matrix matrix to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets a float on a uniform variable.
  1030. * @param uniformName Name of the variable.
  1031. * @param value value to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setFloat = function (uniformName, value) {
  1035. var cache = this._valueCache[uniformName];
  1036. if (cache !== undefined && cache === value)
  1037. return this;
  1038. this._valueCache[uniformName] = value;
  1039. this._engine.setFloat(this.getUniform(uniformName), value);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a boolean on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param bool value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setBool = function (uniformName, bool) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === bool)
  1051. return this;
  1052. this._valueCache[uniformName] = bool;
  1053. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a Vector2 on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param vector2 vector2 to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1063. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1064. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1065. }
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float2 on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param x First float in float2.
  1072. * @param y Second float in float2.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1076. if (this._cacheFloat2(uniformName, x, y)) {
  1077. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector3 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector3 Value to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1088. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1089. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float3 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float3.
  1097. * @param y Second float in float3.
  1098. * @param z Third float in float3.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1102. if (this._cacheFloat3(uniformName, x, y, z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a Vector4 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param vector4 Value to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1114. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1115. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a float4 on a uniform variable.
  1121. * @param uniformName Name of the variable.
  1122. * @param x First float in float4.
  1123. * @param y Second float in float4.
  1124. * @param z Third float in float4.
  1125. * @param w Fourth float in float4.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Sets a Color3 on a uniform variable.
  1136. * @param uniformName Name of the variable.
  1137. * @param color3 Value to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setColor3 = function (uniformName, color3) {
  1141. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1142. this._engine.setColor3(this.getUniform(uniformName), color3);
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a Color4 on a uniform variable.
  1148. * @param uniformName Name of the variable.
  1149. * @param color3 Value to be set.
  1150. * @param alpha Alpha value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1154. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color4 on a uniform variable
  1161. * @param uniformName defines the name of the variable
  1162. * @param color4 defines the value to be set
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1166. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1167. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Resets the cache of effects.
  1173. */
  1174. Effect.ResetCache = function () {
  1175. Effect._baseCache = {};
  1176. };
  1177. Effect._uniqueIdSeed = 0;
  1178. Effect._baseCache = {};
  1179. // Statics
  1180. /**
  1181. * Store of each shader (The can be looked up using effect.key)
  1182. */
  1183. Effect.ShadersStore = {};
  1184. /**
  1185. * Store of each included file for a shader (The can be looked up using effect.key)
  1186. */
  1187. Effect.IncludesShadersStore = {};
  1188. return Effect;
  1189. }());
  1190. BABYLON.Effect = Effect;
  1191. })(BABYLON || (BABYLON = {}));
  1192. //# sourceMappingURL=babylon.effect.js.map
  1193. //# sourceMappingURL=babylon.types.js.map
  1194. var BABYLON;
  1195. (function (BABYLON) {
  1196. var KeyboardEventTypes = /** @class */ (function () {
  1197. function KeyboardEventTypes() {
  1198. }
  1199. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1200. get: function () {
  1201. return KeyboardEventTypes._KEYDOWN;
  1202. },
  1203. enumerable: true,
  1204. configurable: true
  1205. });
  1206. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1207. get: function () {
  1208. return KeyboardEventTypes._KEYUP;
  1209. },
  1210. enumerable: true,
  1211. configurable: true
  1212. });
  1213. KeyboardEventTypes._KEYDOWN = 0x01;
  1214. KeyboardEventTypes._KEYUP = 0x02;
  1215. return KeyboardEventTypes;
  1216. }());
  1217. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1218. var KeyboardInfo = /** @class */ (function () {
  1219. function KeyboardInfo(type, event) {
  1220. this.type = type;
  1221. this.event = event;
  1222. }
  1223. return KeyboardInfo;
  1224. }());
  1225. BABYLON.KeyboardInfo = KeyboardInfo;
  1226. /**
  1227. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1228. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1229. */
  1230. var KeyboardInfoPre = /** @class */ (function (_super) {
  1231. __extends(KeyboardInfoPre, _super);
  1232. function KeyboardInfoPre(type, event) {
  1233. var _this = _super.call(this, type, event) || this;
  1234. _this.skipOnPointerObservable = false;
  1235. return _this;
  1236. }
  1237. return KeyboardInfoPre;
  1238. }(KeyboardInfo));
  1239. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1240. })(BABYLON || (BABYLON = {}));
  1241. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1242. var BABYLON;
  1243. (function (BABYLON) {
  1244. var PointerEventTypes = /** @class */ (function () {
  1245. function PointerEventTypes() {
  1246. }
  1247. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERDOWN;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERUP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERMOVE;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERWHEEL;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERPICK;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERTAP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOUBLETAP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. PointerEventTypes._POINTERDOWN = 0x01;
  1297. PointerEventTypes._POINTERUP = 0x02;
  1298. PointerEventTypes._POINTERMOVE = 0x04;
  1299. PointerEventTypes._POINTERWHEEL = 0x08;
  1300. PointerEventTypes._POINTERPICK = 0x10;
  1301. PointerEventTypes._POINTERTAP = 0x20;
  1302. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1303. return PointerEventTypes;
  1304. }());
  1305. BABYLON.PointerEventTypes = PointerEventTypes;
  1306. var PointerInfoBase = /** @class */ (function () {
  1307. function PointerInfoBase(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return PointerInfoBase;
  1312. }());
  1313. BABYLON.PointerInfoBase = PointerInfoBase;
  1314. /**
  1315. * This class is used to store pointer related info for the onPrePointerObservable event.
  1316. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1317. */
  1318. var PointerInfoPre = /** @class */ (function (_super) {
  1319. __extends(PointerInfoPre, _super);
  1320. function PointerInfoPre(type, event, localX, localY) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1324. return _this;
  1325. }
  1326. return PointerInfoPre;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfoPre = PointerInfoPre;
  1329. /**
  1330. * This type contains all the data related to a pointer event in Babylon.js.
  1331. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1332. */
  1333. var PointerInfo = /** @class */ (function (_super) {
  1334. __extends(PointerInfo, _super);
  1335. function PointerInfo(type, event, pickInfo) {
  1336. var _this = _super.call(this, type, event) || this;
  1337. _this.pickInfo = pickInfo;
  1338. return _this;
  1339. }
  1340. return PointerInfo;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfo = PointerInfo;
  1343. })(BABYLON || (BABYLON = {}));
  1344. //# sourceMappingURL=babylon.pointerEvents.js.map
  1345. var BABYLON;
  1346. (function (BABYLON) {
  1347. BABYLON.ToGammaSpace = 1 / 2.2;
  1348. BABYLON.ToLinearSpace = 2.2;
  1349. BABYLON.Epsilon = 0.001;
  1350. /**
  1351. * Class used to hold a RBG color
  1352. */
  1353. var Color3 = /** @class */ (function () {
  1354. /**
  1355. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1356. * @param r defines the red component (between 0 and 1, default is 0)
  1357. * @param g defines the green component (between 0 and 1, default is 0)
  1358. * @param b defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. function Color3(
  1361. /**
  1362. * Defines the red component (between 0 and 1, default is 0)
  1363. */
  1364. r,
  1365. /**
  1366. * Defines the green component (between 0 and 1, default is 0)
  1367. */
  1368. g,
  1369. /**
  1370. * Defines the blue component (between 0 and 1, default is 0)
  1371. */
  1372. b) {
  1373. if (r === void 0) { r = 0; }
  1374. if (g === void 0) { g = 0; }
  1375. if (b === void 0) { b = 0; }
  1376. this.r = r;
  1377. this.g = g;
  1378. this.b = b;
  1379. }
  1380. /**
  1381. * Creates a string with the Color3 current values
  1382. * @returns the string representation of the Color3 object
  1383. */
  1384. Color3.prototype.toString = function () {
  1385. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1386. };
  1387. /**
  1388. * Returns the string "Color3"
  1389. * @returns "Color3"
  1390. */
  1391. Color3.prototype.getClassName = function () {
  1392. return "Color3";
  1393. };
  1394. /**
  1395. * Compute the Color3 hash code
  1396. * @returns an unique number that can be used to hash Color3 objects
  1397. */
  1398. Color3.prototype.getHashCode = function () {
  1399. var hash = this.r || 0;
  1400. hash = (hash * 397) ^ (this.g || 0);
  1401. hash = (hash * 397) ^ (this.b || 0);
  1402. return hash;
  1403. };
  1404. // Operators
  1405. /**
  1406. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1407. * @param array defines the array where to store the r,g,b components
  1408. * @param index defines an optional index in the target array to define where to start storing values
  1409. * @returns the current Color3 object
  1410. */
  1411. Color3.prototype.toArray = function (array, index) {
  1412. if (index === undefined) {
  1413. index = 0;
  1414. }
  1415. array[index] = this.r;
  1416. array[index + 1] = this.g;
  1417. array[index + 2] = this.b;
  1418. return this;
  1419. };
  1420. /**
  1421. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1422. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1423. * @returns a new {BABYLON.Color4} object
  1424. */
  1425. Color3.prototype.toColor4 = function (alpha) {
  1426. if (alpha === void 0) { alpha = 1; }
  1427. return new Color4(this.r, this.g, this.b, alpha);
  1428. };
  1429. /**
  1430. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1431. * @returns the new array
  1432. */
  1433. Color3.prototype.asArray = function () {
  1434. var result = new Array();
  1435. this.toArray(result, 0);
  1436. return result;
  1437. };
  1438. /**
  1439. * Returns the luminance value
  1440. * @returns a float value
  1441. */
  1442. Color3.prototype.toLuminance = function () {
  1443. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1444. };
  1445. /**
  1446. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1447. * @param otherColor defines the second operand
  1448. * @returns the new Color3 object
  1449. */
  1450. Color3.prototype.multiply = function (otherColor) {
  1451. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1452. };
  1453. /**
  1454. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1455. * @param otherColor defines the second operand
  1456. * @param result defines the Color3 object where to store the result
  1457. * @returns the current Color3
  1458. */
  1459. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1460. result.r = this.r * otherColor.r;
  1461. result.g = this.g * otherColor.g;
  1462. result.b = this.b * otherColor.b;
  1463. return this;
  1464. };
  1465. /**
  1466. * Determines equality between Color3 objects
  1467. * @param otherColor defines the second operand
  1468. * @returns true if the rgb values are equal to the passed ones
  1469. */
  1470. Color3.prototype.equals = function (otherColor) {
  1471. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1472. };
  1473. /**
  1474. * Determines equality between the current Color3 object and a set of r,b,g values
  1475. * @param r defines the red component to check
  1476. * @param g defines the green component to check
  1477. * @param b defines the blue component to check
  1478. * @returns true if the rgb values are equal to the passed ones
  1479. */
  1480. Color3.prototype.equalsFloats = function (r, g, b) {
  1481. return this.r === r && this.g === g && this.b === b;
  1482. };
  1483. /**
  1484. * Multiplies in place each rgb value by scale
  1485. * @param scale defines the scaling factor
  1486. * @returns the updated Color3.
  1487. */
  1488. Color3.prototype.scale = function (scale) {
  1489. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1490. };
  1491. /**
  1492. * Multiplies the rgb values by scale and stores the result into "result"
  1493. * @param scale defines the scaling factor
  1494. * @param result defines the Color3 object where to store the result
  1495. * @returns the unmodified current Color3.
  1496. */
  1497. Color3.prototype.scaleToRef = function (scale, result) {
  1498. result.r = this.r * scale;
  1499. result.g = this.g * scale;
  1500. result.b = this.b * scale;
  1501. return this;
  1502. };
  1503. /**
  1504. * Clamps the rgb values by the min and max values and stores the result into "result"
  1505. * @param min defines minimum clamping value (default is 0)
  1506. * @param max defines maximum clamping value (default is 1)
  1507. * @param result defines color to store the result into
  1508. * @returns the original Color3
  1509. */
  1510. Color3.prototype.clampToRef = function (min, max, result) {
  1511. if (min === void 0) { min = 0; }
  1512. if (max === void 0) { max = 1; }
  1513. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1514. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1515. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1516. return this;
  1517. };
  1518. /**
  1519. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3
  1522. */
  1523. Color3.prototype.add = function (otherColor) {
  1524. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1525. };
  1526. /**
  1527. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines Color3 object to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.addToRef = function (otherColor, result) {
  1533. result.r = this.r + otherColor.r;
  1534. result.g = this.g + otherColor.g;
  1535. result.b = this.b + otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1540. * @param otherColor defines the second operand
  1541. * @returns the new Color3
  1542. */
  1543. Color3.prototype.subtract = function (otherColor) {
  1544. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1545. };
  1546. /**
  1547. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1548. * @param otherColor defines the second operand
  1549. * @param result defines Color3 object to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.subtractToRef = function (otherColor, result) {
  1553. result.r = this.r - otherColor.r;
  1554. result.g = this.g - otherColor.g;
  1555. result.b = this.b - otherColor.b;
  1556. return this;
  1557. };
  1558. /**
  1559. * Copy the current object
  1560. * @returns a new Color3 copied the current one
  1561. */
  1562. Color3.prototype.clone = function () {
  1563. return new Color3(this.r, this.g, this.b);
  1564. };
  1565. /**
  1566. * Copies the rgb values from the source in the current Color3
  1567. * @param source defines the source Color3 object
  1568. * @returns the updated Color3 object
  1569. */
  1570. Color3.prototype.copyFrom = function (source) {
  1571. this.r = source.r;
  1572. this.g = source.g;
  1573. this.b = source.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Updates the Color3 rgb values from the passed floats
  1578. * @param r defines the red component to read from
  1579. * @param g defines the green component to read from
  1580. * @param b defines the blue component to read from
  1581. * @returns the current Color3 object
  1582. */
  1583. Color3.prototype.copyFromFloats = function (r, g, b) {
  1584. this.r = r;
  1585. this.g = g;
  1586. this.b = b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Updates the Color3 rgb values from the passed floats
  1591. * @param r defines the red component to read from
  1592. * @param g defines the green component to read from
  1593. * @param b defines the blue component to read from
  1594. * @returns the current Color3 object
  1595. */
  1596. Color3.prototype.set = function (r, g, b) {
  1597. return this.copyFromFloats(r, g, b);
  1598. };
  1599. /**
  1600. * Compute the Color3 hexadecimal code as a string
  1601. * @returns a string containing the hexadecimal representation of the Color3 object
  1602. */
  1603. Color3.prototype.toHexString = function () {
  1604. var intR = (this.r * 255) | 0;
  1605. var intG = (this.g * 255) | 0;
  1606. var intB = (this.b * 255) | 0;
  1607. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1608. };
  1609. /**
  1610. * Computes a new Color3 converted from the current one to linear space
  1611. * @returns a new Color3 object
  1612. */
  1613. Color3.prototype.toLinearSpace = function () {
  1614. var convertedColor = new Color3();
  1615. this.toLinearSpaceToRef(convertedColor);
  1616. return convertedColor;
  1617. };
  1618. /**
  1619. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1620. * @param convertedColor defines the Color3 object where to store the linear space version
  1621. * @returns the unmodified Color3
  1622. */
  1623. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1624. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1625. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1626. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1627. return this;
  1628. };
  1629. /**
  1630. * Computes a new Color3 converted from the current one to gamma space
  1631. * @returns a new Color3 object
  1632. */
  1633. Color3.prototype.toGammaSpace = function () {
  1634. var convertedColor = new Color3();
  1635. this.toGammaSpaceToRef(convertedColor);
  1636. return convertedColor;
  1637. };
  1638. /**
  1639. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1640. * @param convertedColor defines the Color3 object where to store the gamma space version
  1641. * @returns the unmodified Color3
  1642. */
  1643. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1644. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1645. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1646. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1647. return this;
  1648. };
  1649. // Statics
  1650. /**
  1651. * Creates a new Color3 from the string containing valid hexadecimal values
  1652. * @param hex defines a string containing valid hexadecimal values
  1653. * @returns a new Color3 object
  1654. */
  1655. Color3.FromHexString = function (hex) {
  1656. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1657. return new Color3(0, 0, 0);
  1658. }
  1659. var r = parseInt(hex.substring(1, 3), 16);
  1660. var g = parseInt(hex.substring(3, 5), 16);
  1661. var b = parseInt(hex.substring(5, 7), 16);
  1662. return Color3.FromInts(r, g, b);
  1663. };
  1664. /**
  1665. * Creates a new Vector3 from the starting index of the passed array
  1666. * @param array defines the source array
  1667. * @param offset defines an offset in the source array
  1668. * @returns a new Color3 object
  1669. */
  1670. Color3.FromArray = function (array, offset) {
  1671. if (offset === void 0) { offset = 0; }
  1672. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1673. };
  1674. /**
  1675. * Creates a new Color3 from integer values (< 256)
  1676. * @param r defines the red component to read from (value between 0 and 255)
  1677. * @param g defines the green component to read from (value between 0 and 255)
  1678. * @param b defines the blue component to read from (value between 0 and 255)
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.FromInts = function (r, g, b) {
  1682. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1683. };
  1684. /**
  1685. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1686. * @param start defines the start Color3 value
  1687. * @param end defines the end Color3 value
  1688. * @param amount defines the gradient value between start and end
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.Lerp = function (start, end, amount) {
  1692. var r = start.r + ((end.r - start.r) * amount);
  1693. var g = start.g + ((end.g - start.g) * amount);
  1694. var b = start.b + ((end.b - start.b) * amount);
  1695. return new Color3(r, g, b);
  1696. };
  1697. /**
  1698. * Returns a Color3 value containing a red color
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.Red = function () { return new Color3(1, 0, 0); };
  1702. /**
  1703. * Returns a Color3 value containing a green color
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.Green = function () { return new Color3(0, 1, 0); };
  1707. /**
  1708. * Returns a Color3 value containing a blue color
  1709. * @returns a new Color3 object
  1710. */
  1711. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1712. /**
  1713. * Returns a Color3 value containing a black color
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Black = function () { return new Color3(0, 0, 0); };
  1717. /**
  1718. * Returns a Color3 value containing a white color
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.White = function () { return new Color3(1, 1, 1); };
  1722. /**
  1723. * Returns a Color3 value containing a purple color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1727. /**
  1728. * Returns a Color3 value containing a magenta color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1732. /**
  1733. * Returns a Color3 value containing a yellow color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a gray color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1742. /**
  1743. * Returns a Color3 value containing a teal color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1747. /**
  1748. * Returns a Color3 value containing a random color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1752. return Color3;
  1753. }());
  1754. BABYLON.Color3 = Color3;
  1755. /**
  1756. * Class used to hold a RBGA color
  1757. */
  1758. var Color4 = /** @class */ (function () {
  1759. /**
  1760. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1761. * @param r defines the red component (between 0 and 1, default is 0)
  1762. * @param g defines the green component (between 0 and 1, default is 0)
  1763. * @param b defines the blue component (between 0 and 1, default is 0)
  1764. * @param a defines the alpha component (between 0 and 1, default is 1)
  1765. */
  1766. function Color4(
  1767. /**
  1768. * Defines the red component (between 0 and 1, default is 0)
  1769. */
  1770. r,
  1771. /**
  1772. * Defines the green component (between 0 and 1, default is 0)
  1773. */
  1774. g,
  1775. /**
  1776. * Defines the blue component (between 0 and 1, default is 0)
  1777. */
  1778. b,
  1779. /**
  1780. * Defines the alpha component (between 0 and 1, default is 1)
  1781. */
  1782. a) {
  1783. if (r === void 0) { r = 0; }
  1784. if (g === void 0) { g = 0; }
  1785. if (b === void 0) { b = 0; }
  1786. if (a === void 0) { a = 1; }
  1787. this.r = r;
  1788. this.g = g;
  1789. this.b = b;
  1790. this.a = a;
  1791. }
  1792. // Operators
  1793. /**
  1794. * Adds in place the passed Color4 values to the current Color4 object
  1795. * @param right defines the second operand
  1796. * @returns the current updated Color4 object
  1797. */
  1798. Color4.prototype.addInPlace = function (right) {
  1799. this.r += right.r;
  1800. this.g += right.g;
  1801. this.b += right.b;
  1802. this.a += right.a;
  1803. return this;
  1804. };
  1805. /**
  1806. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1807. * @returns the new array
  1808. */
  1809. Color4.prototype.asArray = function () {
  1810. var result = new Array();
  1811. this.toArray(result, 0);
  1812. return result;
  1813. };
  1814. /**
  1815. * Stores from the starting index in the passed array the Color4 successive values
  1816. * @param array defines the array where to store the r,g,b components
  1817. * @param index defines an optional index in the target array to define where to start storing values
  1818. * @returns the current Color4 object
  1819. */
  1820. Color4.prototype.toArray = function (array, index) {
  1821. if (index === undefined) {
  1822. index = 0;
  1823. }
  1824. array[index] = this.r;
  1825. array[index + 1] = this.g;
  1826. array[index + 2] = this.b;
  1827. array[index + 3] = this.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1832. * @param right defines the second operand
  1833. * @returns a new Color4 object
  1834. */
  1835. Color4.prototype.add = function (right) {
  1836. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1837. };
  1838. /**
  1839. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1840. * @param right defines the second operand
  1841. * @returns a new Color4 object
  1842. */
  1843. Color4.prototype.subtract = function (right) {
  1844. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1845. };
  1846. /**
  1847. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1848. * @param right defines the second operand
  1849. * @param result defines the Color4 object where to store the result
  1850. * @returns the current Color4 object
  1851. */
  1852. Color4.prototype.subtractToRef = function (right, result) {
  1853. result.r = this.r - right.r;
  1854. result.g = this.g - right.g;
  1855. result.b = this.b - right.b;
  1856. result.a = this.a - right.a;
  1857. return this;
  1858. };
  1859. /**
  1860. * Creates a new Color4 with the current Color4 values multiplied by scale
  1861. * @param scale defines the scaling factor to apply
  1862. * @returns a new Color4 object
  1863. */
  1864. Color4.prototype.scale = function (scale) {
  1865. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1866. };
  1867. /**
  1868. * Multiplies the current Color4 values by scale and stores the result in "result"
  1869. * @param scale defines the scaling factor to apply
  1870. * @param result defines the Color4 object where to store the result
  1871. * @returns the current Color4.
  1872. */
  1873. Color4.prototype.scaleToRef = function (scale, result) {
  1874. result.r = this.r * scale;
  1875. result.g = this.g * scale;
  1876. result.b = this.b * scale;
  1877. result.a = this.a * scale;
  1878. return this;
  1879. };
  1880. /**
  1881. * Clamps the rgb values by the min and max values and stores the result into "result"
  1882. * @param min defines minimum clamping value (default is 0)
  1883. * @param max defines maximum clamping value (default is 1)
  1884. * @param result defines color to store the result into.
  1885. * @returns the cuurent Color4
  1886. */
  1887. Color4.prototype.clampToRef = function (min, max, result) {
  1888. if (min === void 0) { min = 0; }
  1889. if (max === void 0) { max = 1; }
  1890. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1891. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1892. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1893. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1894. return this;
  1895. };
  1896. /**
  1897. * Multipy an Color4 value by another and return a new Color4 object
  1898. * @param color defines the Color4 value to multiply by
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.multiply = function (color) {
  1902. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1903. };
  1904. /**
  1905. * Multipy a Color4 value by another and push the result in a reference value
  1906. * @param color defines the Color4 value to multiply by
  1907. * @param result defines the Color4 to fill the result in
  1908. * @returns the result Color4
  1909. */
  1910. Color4.prototype.multiplyToRef = function (color, result) {
  1911. result.r = this.r * color.r;
  1912. result.g = this.g * color.g;
  1913. result.b = this.b * color.b;
  1914. result.a = this.a * color.a;
  1915. return result;
  1916. };
  1917. /**
  1918. * Creates a string with the Color4 current values
  1919. * @returns the string representation of the Color4 object
  1920. */
  1921. Color4.prototype.toString = function () {
  1922. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1923. };
  1924. /**
  1925. * Returns the string "Color4"
  1926. * @returns "Color4"
  1927. */
  1928. Color4.prototype.getClassName = function () {
  1929. return "Color4";
  1930. };
  1931. /**
  1932. * Compute the Color4 hash code
  1933. * @returns an unique number that can be used to hash Color4 objects
  1934. */
  1935. Color4.prototype.getHashCode = function () {
  1936. var hash = this.r || 0;
  1937. hash = (hash * 397) ^ (this.g || 0);
  1938. hash = (hash * 397) ^ (this.b || 0);
  1939. hash = (hash * 397) ^ (this.a || 0);
  1940. return hash;
  1941. };
  1942. /**
  1943. * Creates a new Color4 copied from the current one
  1944. * @returns a new Color4 object
  1945. */
  1946. Color4.prototype.clone = function () {
  1947. return new Color4(this.r, this.g, this.b, this.a);
  1948. };
  1949. /**
  1950. * Copies the passed Color4 values into the current one
  1951. * @param source defines the source Color4 object
  1952. * @returns the current updated Color4 object
  1953. */
  1954. Color4.prototype.copyFrom = function (source) {
  1955. this.r = source.r;
  1956. this.g = source.g;
  1957. this.b = source.b;
  1958. this.a = source.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Copies the passed float values into the current one
  1963. * @param r defines the red component to read from
  1964. * @param g defines the green component to read from
  1965. * @param b defines the blue component to read from
  1966. * @param a defines the alpha component to read from
  1967. * @returns the current updated Color4 object
  1968. */
  1969. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1970. this.r = r;
  1971. this.g = g;
  1972. this.b = b;
  1973. this.a = a;
  1974. return this;
  1975. };
  1976. /**
  1977. * Copies the passed float values into the current one
  1978. * @param r defines the red component to read from
  1979. * @param g defines the green component to read from
  1980. * @param b defines the blue component to read from
  1981. * @param a defines the alpha component to read from
  1982. * @returns the current updated Color4 object
  1983. */
  1984. Color4.prototype.set = function (r, g, b, a) {
  1985. return this.copyFromFloats(r, g, b, a);
  1986. };
  1987. /**
  1988. * Compute the Color4 hexadecimal code as a string
  1989. * @returns a string containing the hexadecimal representation of the Color4 object
  1990. */
  1991. Color4.prototype.toHexString = function () {
  1992. var intR = (this.r * 255) | 0;
  1993. var intG = (this.g * 255) | 0;
  1994. var intB = (this.b * 255) | 0;
  1995. var intA = (this.a * 255) | 0;
  1996. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1997. };
  1998. /**
  1999. * Computes a new Color4 converted from the current one to linear space
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.toLinearSpace = function () {
  2003. var convertedColor = new Color4();
  2004. this.toLinearSpaceToRef(convertedColor);
  2005. return convertedColor;
  2006. };
  2007. /**
  2008. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2009. * @param convertedColor defines the Color4 object where to store the linear space version
  2010. * @returns the unmodified Color4
  2011. */
  2012. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2013. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2014. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2015. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2016. convertedColor.a = this.a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Computes a new Color4 converted from the current one to gamma space
  2021. * @returns a new Color4 object
  2022. */
  2023. Color4.prototype.toGammaSpace = function () {
  2024. var convertedColor = new Color4();
  2025. this.toGammaSpaceToRef(convertedColor);
  2026. return convertedColor;
  2027. };
  2028. /**
  2029. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2030. * @param convertedColor defines the Color4 object where to store the gamma space version
  2031. * @returns the unmodified Color4
  2032. */
  2033. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2034. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2035. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2036. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2037. convertedColor.a = this.a;
  2038. return this;
  2039. };
  2040. // Statics
  2041. /**
  2042. * Creates a new Color4 from the string containing valid hexadecimal values
  2043. * @param hex defines a string containing valid hexadecimal values
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.FromHexString = function (hex) {
  2047. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2048. return new Color4(0.0, 0.0, 0.0, 0.0);
  2049. }
  2050. var r = parseInt(hex.substring(1, 3), 16);
  2051. var g = parseInt(hex.substring(3, 5), 16);
  2052. var b = parseInt(hex.substring(5, 7), 16);
  2053. var a = parseInt(hex.substring(7, 9), 16);
  2054. return Color4.FromInts(r, g, b, a);
  2055. };
  2056. /**
  2057. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2058. * @param left defines the start value
  2059. * @param right defines the end value
  2060. * @param amount defines the gradient factor
  2061. * @returns a new Color4 object
  2062. */
  2063. Color4.Lerp = function (left, right, amount) {
  2064. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2065. Color4.LerpToRef(left, right, amount, result);
  2066. return result;
  2067. };
  2068. /**
  2069. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2070. * @param left defines the start value
  2071. * @param right defines the end value
  2072. * @param amount defines the gradient factor
  2073. * @param result defines the Color4 object where to store data
  2074. */
  2075. Color4.LerpToRef = function (left, right, amount, result) {
  2076. result.r = left.r + (right.r - left.r) * amount;
  2077. result.g = left.g + (right.g - left.g) * amount;
  2078. result.b = left.b + (right.b - left.b) * amount;
  2079. result.a = left.a + (right.a - left.a) * amount;
  2080. };
  2081. /**
  2082. * Creates a new Color4 from the starting index element of the passed array
  2083. * @param array defines the source array to read from
  2084. * @param offset defines the offset in the source array
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromArray = function (array, offset) {
  2088. if (offset === void 0) { offset = 0; }
  2089. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2090. };
  2091. /**
  2092. * Creates a new Color3 from integer values (< 256)
  2093. * @param r defines the red component to read from (value between 0 and 255)
  2094. * @param g defines the green component to read from (value between 0 and 255)
  2095. * @param b defines the blue component to read from (value between 0 and 255)
  2096. * @param a defines the alpha component to read from (value between 0 and 255)
  2097. * @returns a new Color3 object
  2098. */
  2099. Color4.FromInts = function (r, g, b, a) {
  2100. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2101. };
  2102. /**
  2103. * Check the content of a given array and convert it to an array containing RGBA data
  2104. * If the original array was already containing count * 4 values then it is returned directly
  2105. * @param colors defines the array to check
  2106. * @param count defines the number of RGBA data to expect
  2107. * @returns an array containing count * 4 values (RGBA)
  2108. */
  2109. Color4.CheckColors4 = function (colors, count) {
  2110. // Check if color3 was used
  2111. if (colors.length === count * 3) {
  2112. var colors4 = [];
  2113. for (var index = 0; index < colors.length; index += 3) {
  2114. var newIndex = (index / 3) * 4;
  2115. colors4[newIndex] = colors[index];
  2116. colors4[newIndex + 1] = colors[index + 1];
  2117. colors4[newIndex + 2] = colors[index + 2];
  2118. colors4[newIndex + 3] = 1.0;
  2119. }
  2120. return colors4;
  2121. }
  2122. return colors;
  2123. };
  2124. return Color4;
  2125. }());
  2126. BABYLON.Color4 = Color4;
  2127. var Vector2 = /** @class */ (function () {
  2128. /**
  2129. * Creates a new Vector2 from the passed x and y coordinates.
  2130. */
  2131. function Vector2(x, y) {
  2132. this.x = x;
  2133. this.y = y;
  2134. }
  2135. /**
  2136. * Returns a string with the Vector2 coordinates.
  2137. */
  2138. Vector2.prototype.toString = function () {
  2139. return "{X: " + this.x + " Y:" + this.y + "}";
  2140. };
  2141. /**
  2142. * Returns the string "Vector2"
  2143. */
  2144. Vector2.prototype.getClassName = function () {
  2145. return "Vector2";
  2146. };
  2147. /**
  2148. * Returns the Vector2 hash code as a number.
  2149. */
  2150. Vector2.prototype.getHashCode = function () {
  2151. var hash = this.x || 0;
  2152. hash = (hash * 397) ^ (this.y || 0);
  2153. return hash;
  2154. };
  2155. // Operators
  2156. /**
  2157. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2158. * Returns the Vector2.
  2159. */
  2160. Vector2.prototype.toArray = function (array, index) {
  2161. if (index === void 0) { index = 0; }
  2162. array[index] = this.x;
  2163. array[index + 1] = this.y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Returns a new array with 2 elements : the Vector2 coordinates.
  2168. */
  2169. Vector2.prototype.asArray = function () {
  2170. var result = new Array();
  2171. this.toArray(result, 0);
  2172. return result;
  2173. };
  2174. /**
  2175. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2176. * Returns the updated Vector2.
  2177. */
  2178. Vector2.prototype.copyFrom = function (source) {
  2179. this.x = source.x;
  2180. this.y = source.y;
  2181. return this;
  2182. };
  2183. /**
  2184. * Sets the Vector2 coordinates with the passed floats.
  2185. * Returns the updated Vector2.
  2186. */
  2187. Vector2.prototype.copyFromFloats = function (x, y) {
  2188. this.x = x;
  2189. this.y = y;
  2190. return this;
  2191. };
  2192. /**
  2193. * Sets the Vector2 coordinates with the passed floats.
  2194. * Returns the updated Vector2.
  2195. */
  2196. Vector2.prototype.set = function (x, y) {
  2197. return this.copyFromFloats(x, y);
  2198. };
  2199. /**
  2200. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2201. */
  2202. Vector2.prototype.add = function (otherVector) {
  2203. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2204. };
  2205. /**
  2206. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2207. * Returns the Vector2.
  2208. */
  2209. Vector2.prototype.addToRef = function (otherVector, result) {
  2210. result.x = this.x + otherVector.x;
  2211. result.y = this.y + otherVector.y;
  2212. return this;
  2213. };
  2214. /**
  2215. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2216. * Returns the updated Vector2.
  2217. */
  2218. Vector2.prototype.addInPlace = function (otherVector) {
  2219. this.x += otherVector.x;
  2220. this.y += otherVector.y;
  2221. return this;
  2222. };
  2223. /**
  2224. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2225. */
  2226. Vector2.prototype.addVector3 = function (otherVector) {
  2227. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2228. };
  2229. /**
  2230. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2231. */
  2232. Vector2.prototype.subtract = function (otherVector) {
  2233. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2234. };
  2235. /**
  2236. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2237. * Returns the Vector2.
  2238. */
  2239. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2240. result.x = this.x - otherVector.x;
  2241. result.y = this.y - otherVector.y;
  2242. return this;
  2243. };
  2244. /**
  2245. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2246. * Returns the updated Vector2.
  2247. */
  2248. Vector2.prototype.subtractInPlace = function (otherVector) {
  2249. this.x -= otherVector.x;
  2250. this.y -= otherVector.y;
  2251. return this;
  2252. };
  2253. /**
  2254. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2255. * Returns the updated Vector2.
  2256. */
  2257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2258. this.x *= otherVector.x;
  2259. this.y *= otherVector.y;
  2260. return this;
  2261. };
  2262. /**
  2263. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2264. */
  2265. Vector2.prototype.multiply = function (otherVector) {
  2266. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2267. };
  2268. /**
  2269. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2270. * Returns the Vector2.
  2271. */
  2272. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2273. result.x = this.x * otherVector.x;
  2274. result.y = this.y * otherVector.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2279. */
  2280. Vector2.prototype.multiplyByFloats = function (x, y) {
  2281. return new Vector2(this.x * x, this.y * y);
  2282. };
  2283. /**
  2284. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2285. */
  2286. Vector2.prototype.divide = function (otherVector) {
  2287. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2288. };
  2289. /**
  2290. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2291. * Returns the Vector2.
  2292. */
  2293. Vector2.prototype.divideToRef = function (otherVector, result) {
  2294. result.x = this.x / otherVector.x;
  2295. result.y = this.y / otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Divides the current Vector3 coordinates by the passed ones.
  2300. * Returns the updated Vector3.
  2301. */
  2302. Vector2.prototype.divideInPlace = function (otherVector) {
  2303. return this.divideToRef(otherVector, this);
  2304. };
  2305. /**
  2306. * Returns a new Vector2 with current Vector2 negated coordinates.
  2307. */
  2308. Vector2.prototype.negate = function () {
  2309. return new Vector2(-this.x, -this.y);
  2310. };
  2311. /**
  2312. * Multiply the Vector2 coordinates by scale.
  2313. * Returns the updated Vector2.
  2314. */
  2315. Vector2.prototype.scaleInPlace = function (scale) {
  2316. this.x *= scale;
  2317. this.y *= scale;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2322. */
  2323. Vector2.prototype.scale = function (scale) {
  2324. return new Vector2(this.x * scale, this.y * scale);
  2325. };
  2326. /**
  2327. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2328. */
  2329. Vector2.prototype.equals = function (otherVector) {
  2330. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2331. };
  2332. /**
  2333. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2334. */
  2335. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2336. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2337. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2338. };
  2339. // Properties
  2340. /**
  2341. * Returns the vector length (float).
  2342. */
  2343. Vector2.prototype.length = function () {
  2344. return Math.sqrt(this.x * this.x + this.y * this.y);
  2345. };
  2346. /**
  2347. * Returns the vector squared length (float);
  2348. */
  2349. Vector2.prototype.lengthSquared = function () {
  2350. return (this.x * this.x + this.y * this.y);
  2351. };
  2352. // Methods
  2353. /**
  2354. * Normalize the vector.
  2355. * Returns the updated Vector2.
  2356. */
  2357. Vector2.prototype.normalize = function () {
  2358. var len = this.length();
  2359. if (len === 0)
  2360. return this;
  2361. var num = 1.0 / len;
  2362. this.x *= num;
  2363. this.y *= num;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 copied from the Vector2.
  2368. */
  2369. Vector2.prototype.clone = function () {
  2370. return new Vector2(this.x, this.y);
  2371. };
  2372. // Statics
  2373. /**
  2374. * Returns a new Vector2(0, 0)
  2375. */
  2376. Vector2.Zero = function () {
  2377. return new Vector2(0, 0);
  2378. };
  2379. /**
  2380. * Returns a new Vector2(1, 1)
  2381. */
  2382. Vector2.One = function () {
  2383. return new Vector2(1, 1);
  2384. };
  2385. /**
  2386. * Returns a new Vector2 set from the passed index element of the passed array.
  2387. */
  2388. Vector2.FromArray = function (array, offset) {
  2389. if (offset === void 0) { offset = 0; }
  2390. return new Vector2(array[offset], array[offset + 1]);
  2391. };
  2392. /**
  2393. * Sets "result" from the passed index element of the passed array.
  2394. */
  2395. Vector2.FromArrayToRef = function (array, offset, result) {
  2396. result.x = array[offset];
  2397. result.y = array[offset + 1];
  2398. };
  2399. /**
  2400. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2401. */
  2402. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2403. var squared = amount * amount;
  2404. var cubed = amount * squared;
  2405. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2406. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2407. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2408. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2409. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2410. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2411. return new Vector2(x, y);
  2412. };
  2413. /**
  2414. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2415. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2416. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2417. */
  2418. Vector2.Clamp = function (value, min, max) {
  2419. var x = value.x;
  2420. x = (x > max.x) ? max.x : x;
  2421. x = (x < min.x) ? min.x : x;
  2422. var y = value.y;
  2423. y = (y > max.y) ? max.y : y;
  2424. y = (y < min.y) ? min.y : y;
  2425. return new Vector2(x, y);
  2426. };
  2427. /**
  2428. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2429. */
  2430. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2431. var squared = amount * amount;
  2432. var cubed = amount * squared;
  2433. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2434. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2435. var part3 = (cubed - (2.0 * squared)) + amount;
  2436. var part4 = cubed - squared;
  2437. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2438. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2439. return new Vector2(x, y);
  2440. };
  2441. /**
  2442. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2443. */
  2444. Vector2.Lerp = function (start, end, amount) {
  2445. var x = start.x + ((end.x - start.x) * amount);
  2446. var y = start.y + ((end.y - start.y) * amount);
  2447. return new Vector2(x, y);
  2448. };
  2449. /**
  2450. * Returns the dot product (float) of the vector "left" and the vector "right".
  2451. */
  2452. Vector2.Dot = function (left, right) {
  2453. return left.x * right.x + left.y * right.y;
  2454. };
  2455. /**
  2456. * Returns a new Vector2 equal to the normalized passed vector.
  2457. */
  2458. Vector2.Normalize = function (vector) {
  2459. var newVector = vector.clone();
  2460. newVector.normalize();
  2461. return newVector;
  2462. };
  2463. /**
  2464. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2465. */
  2466. Vector2.Minimize = function (left, right) {
  2467. var x = (left.x < right.x) ? left.x : right.x;
  2468. var y = (left.y < right.y) ? left.y : right.y;
  2469. return new Vector2(x, y);
  2470. };
  2471. /**
  2472. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2473. */
  2474. Vector2.Maximize = function (left, right) {
  2475. var x = (left.x > right.x) ? left.x : right.x;
  2476. var y = (left.y > right.y) ? left.y : right.y;
  2477. return new Vector2(x, y);
  2478. };
  2479. /**
  2480. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2481. */
  2482. Vector2.Transform = function (vector, transformation) {
  2483. var r = Vector2.Zero();
  2484. Vector2.TransformToRef(vector, transformation, r);
  2485. return r;
  2486. };
  2487. /**
  2488. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2489. */
  2490. Vector2.TransformToRef = function (vector, transformation, result) {
  2491. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2492. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2493. result.x = x;
  2494. result.y = y;
  2495. };
  2496. /**
  2497. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2498. */
  2499. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2500. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2501. var sign = a < 0 ? -1 : 1;
  2502. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2503. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2504. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2505. };
  2506. /**
  2507. * Returns the distance (float) between the vectors "value1" and "value2".
  2508. */
  2509. Vector2.Distance = function (value1, value2) {
  2510. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2511. };
  2512. /**
  2513. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2514. */
  2515. Vector2.DistanceSquared = function (value1, value2) {
  2516. var x = value1.x - value2.x;
  2517. var y = value1.y - value2.y;
  2518. return (x * x) + (y * y);
  2519. };
  2520. /**
  2521. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2522. */
  2523. Vector2.Center = function (value1, value2) {
  2524. var center = value1.add(value2);
  2525. center.scaleInPlace(0.5);
  2526. return center;
  2527. };
  2528. /**
  2529. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2530. */
  2531. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2532. var l2 = Vector2.DistanceSquared(segA, segB);
  2533. if (l2 === 0.0) {
  2534. return Vector2.Distance(p, segA);
  2535. }
  2536. var v = segB.subtract(segA);
  2537. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2538. var proj = segA.add(v.multiplyByFloats(t, t));
  2539. return Vector2.Distance(p, proj);
  2540. };
  2541. return Vector2;
  2542. }());
  2543. BABYLON.Vector2 = Vector2;
  2544. /**
  2545. * Classed used to store (x,y,z) vector representation
  2546. * A Vector3 is the main object used in 3D geometry
  2547. * It can represent etiher the coordinates of a point the space, either a direction
  2548. * Reminder: Babylon.js uses a left handed forward facing system
  2549. */
  2550. var Vector3 = /** @class */ (function () {
  2551. /**
  2552. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2553. * @param x defines the first coordinates (on X axis)
  2554. * @param y defines the second coordinates (on Y axis)
  2555. * @param z defines the third coordinates (on Z axis)
  2556. */
  2557. function Vector3(
  2558. /**
  2559. * Defines the first coordinates (on X axis)
  2560. */
  2561. x,
  2562. /**
  2563. * Defines the second coordinates (on Y axis)
  2564. */
  2565. y,
  2566. /**
  2567. * Defines the third coordinates (on Z axis)
  2568. */
  2569. z) {
  2570. this.x = x;
  2571. this.y = y;
  2572. this.z = z;
  2573. }
  2574. /**
  2575. * Creates a string representation of the Vector3
  2576. * @returns a string with the Vector3 coordinates.
  2577. */
  2578. Vector3.prototype.toString = function () {
  2579. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2580. };
  2581. /**
  2582. * Gets the class name
  2583. * @returns the string "Vector3"
  2584. */
  2585. Vector3.prototype.getClassName = function () {
  2586. return "Vector3";
  2587. };
  2588. /**
  2589. * Creates the Vector3 hash code
  2590. * @returns a number which tends to be unique between Vector3 instances
  2591. */
  2592. Vector3.prototype.getHashCode = function () {
  2593. var hash = this.x || 0;
  2594. hash = (hash * 397) ^ (this.y || 0);
  2595. hash = (hash * 397) ^ (this.z || 0);
  2596. return hash;
  2597. };
  2598. // Operators
  2599. /**
  2600. * Creates an array containing three elements : the coordinates of the Vector3
  2601. * @returns a new array of numbers
  2602. */
  2603. Vector3.prototype.asArray = function () {
  2604. var result = [];
  2605. this.toArray(result, 0);
  2606. return result;
  2607. };
  2608. /**
  2609. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2610. * @param array defines the destination array
  2611. * @param index defines the offset in the destination array
  2612. * @returns the current Vector3
  2613. */
  2614. Vector3.prototype.toArray = function (array, index) {
  2615. if (index === void 0) { index = 0; }
  2616. array[index] = this.x;
  2617. array[index + 1] = this.y;
  2618. array[index + 2] = this.z;
  2619. return this;
  2620. };
  2621. /**
  2622. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2623. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2624. */
  2625. Vector3.prototype.toQuaternion = function () {
  2626. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2631. var cosy = Math.cos(this.y * 0.5);
  2632. var siny = Math.sin(this.y * 0.5);
  2633. result.x = coszMinusx * siny;
  2634. result.y = -sinzMinusx * siny;
  2635. result.z = sinxPlusz * cosy;
  2636. result.w = cosxPlusz * cosy;
  2637. return result;
  2638. };
  2639. /**
  2640. * Adds the passed vector to the current Vector3
  2641. * @param otherVector defines the second operand
  2642. * @returns the current updated Vector3
  2643. */
  2644. Vector3.prototype.addInPlace = function (otherVector) {
  2645. this.x += otherVector.x;
  2646. this.y += otherVector.y;
  2647. this.z += otherVector.z;
  2648. return this;
  2649. };
  2650. /**
  2651. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2652. * @param otherVector defines the second operand
  2653. * @returns the resulting Vector3
  2654. */
  2655. Vector3.prototype.add = function (otherVector) {
  2656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2657. };
  2658. /**
  2659. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2660. * @param otherVector defines the second operand
  2661. * @param result defines the Vector3 object where to store the result
  2662. * @returns the current Vector3
  2663. */
  2664. Vector3.prototype.addToRef = function (otherVector, result) {
  2665. result.x = this.x + otherVector.x;
  2666. result.y = this.y + otherVector.y;
  2667. result.z = this.z + otherVector.z;
  2668. return this;
  2669. };
  2670. /**
  2671. * Subtract the passed vector from the current Vector3
  2672. * @param otherVector defines the second operand
  2673. * @returns the current updated Vector3
  2674. */
  2675. Vector3.prototype.subtractInPlace = function (otherVector) {
  2676. this.x -= otherVector.x;
  2677. this.y -= otherVector.y;
  2678. this.z -= otherVector.z;
  2679. return this;
  2680. };
  2681. /**
  2682. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2683. * @param otherVector defines the second operand
  2684. * @returns the resulting Vector3
  2685. */
  2686. Vector3.prototype.subtract = function (otherVector) {
  2687. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2688. };
  2689. /**
  2690. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2691. * @param otherVector defines the second operand
  2692. * @param result defines the Vector3 object where to store the result
  2693. * @returns the current Vector3
  2694. */
  2695. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2696. result.x = this.x - otherVector.x;
  2697. result.y = this.y - otherVector.y;
  2698. result.z = this.z - otherVector.z;
  2699. return this;
  2700. };
  2701. /**
  2702. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2703. * @param x defines the x coordinate of the operand
  2704. * @param y defines the y coordinate of the operand
  2705. * @param z defines the z coordinate of the operand
  2706. * @returns the resulting Vector3
  2707. */
  2708. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2709. return new Vector3(this.x - x, this.y - y, this.z - z);
  2710. };
  2711. /**
  2712. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2713. * @param x defines the x coordinate of the operand
  2714. * @param y defines the y coordinate of the operand
  2715. * @param z defines the z coordinate of the operand
  2716. * @param result defines the Vector3 object where to store the result
  2717. * @returns the current Vector3
  2718. */
  2719. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2720. result.x = this.x - x;
  2721. result.y = this.y - y;
  2722. result.z = this.z - z;
  2723. return this;
  2724. };
  2725. /**
  2726. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2727. * @returns a new Vector3
  2728. */
  2729. Vector3.prototype.negate = function () {
  2730. return new Vector3(-this.x, -this.y, -this.z);
  2731. };
  2732. /**
  2733. * Multiplies the Vector3 coordinates by the float "scale"
  2734. * @param scale defines the multiplier factor
  2735. * @returns the current updated Vector3
  2736. */
  2737. Vector3.prototype.scaleInPlace = function (scale) {
  2738. this.x *= scale;
  2739. this.y *= scale;
  2740. this.z *= scale;
  2741. return this;
  2742. };
  2743. /**
  2744. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2745. * @param scale defines the multiplier factor
  2746. * @returns a new Vector3
  2747. */
  2748. Vector3.prototype.scale = function (scale) {
  2749. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2750. };
  2751. /**
  2752. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2753. * @param scale defines the multiplier factor
  2754. * @param result defines the Vector3 object where to store the result
  2755. * @returns the current Vector3
  2756. */
  2757. Vector3.prototype.scaleToRef = function (scale, result) {
  2758. result.x = this.x * scale;
  2759. result.y = this.y * scale;
  2760. result.z = this.z * scale;
  2761. return this;
  2762. };
  2763. /**
  2764. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2765. * @param otherVector defines the second operand
  2766. * @returns true if both vectors are equals
  2767. */
  2768. Vector3.prototype.equals = function (otherVector) {
  2769. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2770. };
  2771. /**
  2772. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2773. * @param otherVector defines the second operand
  2774. * @param epsilon defines the minimal distance to define values as equals
  2775. * @returns true if both vectors are distant less than epsilon
  2776. */
  2777. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2779. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2780. };
  2781. /**
  2782. * Returns true if the current Vector3 coordinates equals the passed floats
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @returns true if both vectors are equals
  2787. */
  2788. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2789. return this.x === x && this.y === y && this.z === z;
  2790. };
  2791. /**
  2792. * Multiplies the current Vector3 coordinates by the passed ones
  2793. * @param otherVector defines the second operand
  2794. * @returns the current updated Vector3
  2795. */
  2796. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2797. this.x *= otherVector.x;
  2798. this.y *= otherVector.y;
  2799. this.z *= otherVector.z;
  2800. return this;
  2801. };
  2802. /**
  2803. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2804. * @param otherVector defines the second operand
  2805. * @returns the new Vector3
  2806. */
  2807. Vector3.prototype.multiply = function (otherVector) {
  2808. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2809. };
  2810. /**
  2811. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2812. * @param otherVector defines the second operand
  2813. * @param result defines the Vector3 object where to store the result
  2814. * @returns the current Vector3
  2815. */
  2816. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2817. result.x = this.x * otherVector.x;
  2818. result.y = this.y * otherVector.y;
  2819. result.z = this.z * otherVector.z;
  2820. return this;
  2821. };
  2822. /**
  2823. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2824. * @param x defines the x coordinate of the operand
  2825. * @param y defines the y coordinate of the operand
  2826. * @param z defines the z coordinate of the operand
  2827. * @returns the new Vector3
  2828. */
  2829. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2830. return new Vector3(this.x * x, this.y * y, this.z * z);
  2831. };
  2832. /**
  2833. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2834. * @param otherVector defines the second operand
  2835. * @returns the new Vector3
  2836. */
  2837. Vector3.prototype.divide = function (otherVector) {
  2838. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2839. };
  2840. /**
  2841. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2842. * @param otherVector defines the second operand
  2843. * @param result defines the Vector3 object where to store the result
  2844. * @returns the current Vector3
  2845. */
  2846. Vector3.prototype.divideToRef = function (otherVector, result) {
  2847. result.x = this.x / otherVector.x;
  2848. result.y = this.y / otherVector.y;
  2849. result.z = this.z / otherVector.z;
  2850. return this;
  2851. };
  2852. /**
  2853. * Divides the current Vector3 coordinates by the passed ones.
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.divideInPlace = function (otherVector) {
  2858. return this.divideToRef(otherVector, this);
  2859. };
  2860. /**
  2861. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2862. * @param other defines the second operand
  2863. * @returns the current updated Vector3
  2864. */
  2865. Vector3.prototype.minimizeInPlace = function (other) {
  2866. if (other.x < this.x)
  2867. this.x = other.x;
  2868. if (other.y < this.y)
  2869. this.y = other.y;
  2870. if (other.z < this.z)
  2871. this.z = other.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2876. * @param other defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.maximizeInPlace = function (other) {
  2880. if (other.x > this.x)
  2881. this.x = other.x;
  2882. if (other.y > this.y)
  2883. this.y = other.y;
  2884. if (other.z > this.z)
  2885. this.z = other.z;
  2886. return this;
  2887. };
  2888. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2889. /**
  2890. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2891. */
  2892. get: function () {
  2893. var absX = Math.abs(this.x);
  2894. var absY = Math.abs(this.y);
  2895. if (absX !== absY) {
  2896. return true;
  2897. }
  2898. var absZ = Math.abs(this.z);
  2899. if (absX !== absZ) {
  2900. return true;
  2901. }
  2902. if (absY !== absZ) {
  2903. return true;
  2904. }
  2905. return false;
  2906. },
  2907. enumerable: true,
  2908. configurable: true
  2909. });
  2910. // Properties
  2911. /**
  2912. * Gets the length of the Vector3
  2913. * @returns the length of the Vecto3
  2914. */
  2915. Vector3.prototype.length = function () {
  2916. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2917. };
  2918. /**
  2919. * Gets the squared length of the Vector3
  2920. * @returns squared length of the Vector3
  2921. */
  2922. Vector3.prototype.lengthSquared = function () {
  2923. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2924. };
  2925. /**
  2926. * Normalize the current Vector3.
  2927. * Please note that this is an in place operation.
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.normalize = function () {
  2931. var len = this.length();
  2932. if (len === 0 || len === 1.0)
  2933. return this;
  2934. var num = 1.0 / len;
  2935. this.x *= num;
  2936. this.y *= num;
  2937. this.z *= num;
  2938. return this;
  2939. };
  2940. /**
  2941. * Normalize the current Vector3 to a new vector
  2942. * @returns the new Vector3
  2943. */
  2944. Vector3.prototype.normalizeToNew = function () {
  2945. var normalized = new Vector3(0, 0, 0);
  2946. this.normalizeToRef(normalized);
  2947. return normalized;
  2948. };
  2949. /**
  2950. * Normalize the current Vector3 to the reference
  2951. * @param reference define the Vector3 to update
  2952. * @returns the updated Vector3
  2953. */
  2954. Vector3.prototype.normalizeToRef = function (reference) {
  2955. var len = this.length();
  2956. if (len === 0 || len === 1.0) {
  2957. reference.set(this.x, this.y, this.z);
  2958. return reference;
  2959. }
  2960. var scale = 1.0 / len;
  2961. this.scaleToRef(scale, reference);
  2962. return reference;
  2963. };
  2964. /**
  2965. * Creates a new Vector3 copied from the current Vector3
  2966. * @returns the new Vector3
  2967. */
  2968. Vector3.prototype.clone = function () {
  2969. return new Vector3(this.x, this.y, this.z);
  2970. };
  2971. /**
  2972. * Copies the passed vector coordinates to the current Vector3 ones
  2973. * @param source defines the source Vector3
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.copyFrom = function (source) {
  2977. this.x = source.x;
  2978. this.y = source.y;
  2979. this.z = source.z;
  2980. return this;
  2981. };
  2982. /**
  2983. * Copies the passed floats to the current Vector3 coordinates
  2984. * @param x defines the x coordinate of the operand
  2985. * @param y defines the y coordinate of the operand
  2986. * @param z defines the z coordinate of the operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2990. this.x = x;
  2991. this.y = y;
  2992. this.z = z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Copies the passed floats to the current Vector3 coordinates
  2997. * @param x defines the x coordinate of the operand
  2998. * @param y defines the y coordinate of the operand
  2999. * @param z defines the z coordinate of the operand
  3000. * @returns the current updated Vector3
  3001. */
  3002. Vector3.prototype.set = function (x, y, z) {
  3003. return this.copyFromFloats(x, y, z);
  3004. };
  3005. // Statics
  3006. /**
  3007. * Get the clip factor between two vectors
  3008. * @param vector0 defines the first operand
  3009. * @param vector1 defines the second operand
  3010. * @param axis defines the axis to use
  3011. * @param size defines the size along the axis
  3012. * @returns the clip factor
  3013. */
  3014. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3015. var d0 = Vector3.Dot(vector0, axis) - size;
  3016. var d1 = Vector3.Dot(vector1, axis) - size;
  3017. var s = d0 / (d0 - d1);
  3018. return s;
  3019. };
  3020. /**
  3021. * Get angle between two vectors
  3022. * @param vector0 angle between vector0 and vector1
  3023. * @param vector1 angle between vector0 and vector1
  3024. * @param normal direction of the normal
  3025. * @return the angle between vector0 and vector1
  3026. */
  3027. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3028. var v0 = vector0.clone().normalize();
  3029. var v1 = vector1.clone().normalize();
  3030. var dot = Vector3.Dot(v0, v1);
  3031. var n = Vector3.Cross(v0, v1);
  3032. if (Vector3.Dot(n, normal) > 0) {
  3033. return Math.acos(dot);
  3034. }
  3035. return -Math.acos(dot);
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set from the index "offset" of the passed array
  3039. * @param array defines the source array
  3040. * @param offset defines the offset in the source array
  3041. * @returns the new Vector3
  3042. */
  3043. Vector3.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3048. };
  3049. /**
  3050. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3051. * This function is deprecated. Use FromArray instead
  3052. * @param array defines the source array
  3053. * @param offset defines the offset in the source array
  3054. * @returns the new Vector3
  3055. */
  3056. Vector3.FromFloatArray = function (array, offset) {
  3057. return Vector3.FromArray(array, offset);
  3058. };
  3059. /**
  3060. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3061. * @param array defines the source array
  3062. * @param offset defines the offset in the source array
  3063. * @param result defines the Vector3 where to store the result
  3064. */
  3065. Vector3.FromArrayToRef = function (array, offset, result) {
  3066. result.x = array[offset];
  3067. result.y = array[offset + 1];
  3068. result.z = array[offset + 2];
  3069. };
  3070. /**
  3071. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3072. * This function is deprecated. Use FromArrayToRef instead.
  3073. * @param array defines the source array
  3074. * @param offset defines the offset in the source array
  3075. * @param result defines the Vector3 where to store the result
  3076. */
  3077. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3078. return Vector3.FromArrayToRef(array, offset, result);
  3079. };
  3080. /**
  3081. * Sets the passed vector "result" with the passed floats.
  3082. * @param x defines the x coordinate of the source
  3083. * @param y defines the y coordinate of the source
  3084. * @param z defines the z coordinate of the source
  3085. * @param result defines the Vector3 where to store the result
  3086. */
  3087. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3088. result.x = x;
  3089. result.y = y;
  3090. result.z = z;
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3094. * @returns a new empty Vector3
  3095. */
  3096. Vector3.Zero = function () {
  3097. return new Vector3(0.0, 0.0, 0.0);
  3098. };
  3099. /**
  3100. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3101. * @returns a new unit Vector3
  3102. */
  3103. Vector3.One = function () {
  3104. return new Vector3(1.0, 1.0, 1.0);
  3105. };
  3106. /**
  3107. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3108. * @returns a new up Vector3
  3109. */
  3110. Vector3.Up = function () {
  3111. return new Vector3(0.0, 1.0, 0.0);
  3112. };
  3113. /**
  3114. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3115. * @returns a new forward Vector3
  3116. */
  3117. Vector3.Forward = function () {
  3118. return new Vector3(0.0, 0.0, 1.0);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3122. * @returns a new right Vector3
  3123. */
  3124. Vector3.Right = function () {
  3125. return new Vector3(1.0, 0.0, 0.0);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3129. * @returns a new left Vector3
  3130. */
  3131. Vector3.Left = function () {
  3132. return new Vector3(-1.0, 0.0, 0.0);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3136. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3137. * @param vector defines the Vector3 to transform
  3138. * @param transformation defines the transformation matrix
  3139. * @returns the transformed Vector3
  3140. */
  3141. Vector3.TransformCoordinates = function (vector, transformation) {
  3142. var result = Vector3.Zero();
  3143. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3144. return result;
  3145. };
  3146. /**
  3147. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3148. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3149. * @param vector defines the Vector3 to transform
  3150. * @param transformation defines the transformation matrix
  3151. * @param result defines the Vector3 where to store the result
  3152. */
  3153. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3154. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3155. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3156. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3157. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3158. result.x = x / w;
  3159. result.y = y / w;
  3160. result.z = z / w;
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3164. * This method computes tranformed coordinates only, not transformed direction vectors
  3165. * @param x define the x coordinate of the source vector
  3166. * @param y define the y coordinate of the source vector
  3167. * @param z define the z coordinate of the source vector
  3168. * @param transformation defines the transformation matrix
  3169. * @param result defines the Vector3 where to store the result
  3170. */
  3171. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3172. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3173. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3174. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3175. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3176. result.x = rx / rw;
  3177. result.y = ry / rw;
  3178. result.z = rz / rw;
  3179. };
  3180. /**
  3181. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3182. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3183. * @param vector defines the Vector3 to transform
  3184. * @param transformation defines the transformation matrix
  3185. * @returns the new Vector3
  3186. */
  3187. Vector3.TransformNormal = function (vector, transformation) {
  3188. var result = Vector3.Zero();
  3189. Vector3.TransformNormalToRef(vector, transformation, result);
  3190. return result;
  3191. };
  3192. /**
  3193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3194. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3195. * @param vector defines the Vector3 to transform
  3196. * @param transformation defines the transformation matrix
  3197. * @param result defines the Vector3 where to store the result
  3198. */
  3199. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3200. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3201. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3202. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3203. result.x = x;
  3204. result.y = y;
  3205. result.z = z;
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3209. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3210. * @param x define the x coordinate of the source vector
  3211. * @param y define the y coordinate of the source vector
  3212. * @param z define the z coordinate of the source vector
  3213. * @param transformation defines the transformation matrix
  3214. * @param result defines the Vector3 where to store the result
  3215. */
  3216. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3217. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3218. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3219. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3220. };
  3221. /**
  3222. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3223. * @param value1 defines the first control point
  3224. * @param value2 defines the second control point
  3225. * @param value3 defines the third control point
  3226. * @param value4 defines the fourth control point
  3227. * @param amount defines the amount on the spline to use
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3231. var squared = amount * amount;
  3232. var cubed = amount * squared;
  3233. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3234. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3235. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3236. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3237. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3238. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3239. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3240. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3241. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3242. return new Vector3(x, y, z);
  3243. };
  3244. /**
  3245. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3246. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3247. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3248. * @param value defines the current value
  3249. * @param min defines the lower range value
  3250. * @param max defines the upper range value
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.Clamp = function (value, min, max) {
  3254. var x = value.x;
  3255. x = (x > max.x) ? max.x : x;
  3256. x = (x < min.x) ? min.x : x;
  3257. var y = value.y;
  3258. y = (y > max.y) ? max.y : y;
  3259. y = (y < min.y) ? min.y : y;
  3260. var z = value.z;
  3261. z = (z > max.z) ? max.z : z;
  3262. z = (z < min.z) ? min.z : z;
  3263. return new Vector3(x, y, z);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3267. * @param value1 defines the first control point
  3268. * @param tangent1 defines the first tangent vector
  3269. * @param value2 defines the second control point
  3270. * @param tangent2 defines the second tangent vector
  3271. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3275. var squared = amount * amount;
  3276. var cubed = amount * squared;
  3277. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3278. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3279. var part3 = (cubed - (2.0 * squared)) + amount;
  3280. var part4 = cubed - squared;
  3281. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3282. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3283. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3284. return new Vector3(x, y, z);
  3285. };
  3286. /**
  3287. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3288. * @param start defines the start value
  3289. * @param end defines the end value
  3290. * @param amount max defines amount between both (between 0 and 1)
  3291. * @returns the new Vector3
  3292. */
  3293. Vector3.Lerp = function (start, end, amount) {
  3294. var result = new Vector3(0, 0, 0);
  3295. Vector3.LerpToRef(start, end, amount, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3300. * @param start defines the start value
  3301. * @param end defines the end value
  3302. * @param amount max defines amount between both (between 0 and 1)
  3303. * @param result defines the Vector3 where to store the result
  3304. */
  3305. Vector3.LerpToRef = function (start, end, amount, result) {
  3306. result.x = start.x + ((end.x - start.x) * amount);
  3307. result.y = start.y + ((end.y - start.y) * amount);
  3308. result.z = start.z + ((end.z - start.z) * amount);
  3309. };
  3310. /**
  3311. * Returns the dot product (float) between the vectors "left" and "right"
  3312. * @param left defines the left operand
  3313. * @param right defines the right operand
  3314. * @returns the dot product
  3315. */
  3316. Vector3.Dot = function (left, right) {
  3317. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3321. * The cross product is then orthogonal to both "left" and "right"
  3322. * @param left defines the left operand
  3323. * @param right defines the right operand
  3324. * @returns the cross product
  3325. */
  3326. Vector3.Cross = function (left, right) {
  3327. var result = Vector3.Zero();
  3328. Vector3.CrossToRef(left, right, result);
  3329. return result;
  3330. };
  3331. /**
  3332. * Sets the passed vector "result" with the cross product of "left" and "right"
  3333. * The cross product is then orthogonal to both "left" and "right"
  3334. * @param left defines the left operand
  3335. * @param right defines the right operand
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.CrossToRef = function (left, right, result) {
  3339. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3340. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3341. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3342. result.copyFrom(MathTmp.Vector3[0]);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the normalization of the passed vector
  3346. * @param vector defines the Vector3 to normalize
  3347. * @returns the new Vector3
  3348. */
  3349. Vector3.Normalize = function (vector) {
  3350. var result = Vector3.Zero();
  3351. Vector3.NormalizeToRef(vector, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed vector "result" with the normalization of the passed first vector
  3356. * @param vector defines the Vector3 to normalize
  3357. * @param result defines the Vector3 where to store the result
  3358. */
  3359. Vector3.NormalizeToRef = function (vector, result) {
  3360. result.copyFrom(vector);
  3361. result.normalize();
  3362. };
  3363. /**
  3364. * Project a Vector3 onto screen space
  3365. * @param vector defines the Vector3 to project
  3366. * @param world defines the world matrix to use
  3367. * @param transform defines the transform (view x projection) matrix to use
  3368. * @param viewport defines the screen viewport to use
  3369. * @returns the new Vector3
  3370. */
  3371. Vector3.Project = function (vector, world, transform, viewport) {
  3372. var cw = viewport.width;
  3373. var ch = viewport.height;
  3374. var cx = viewport.x;
  3375. var cy = viewport.y;
  3376. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3377. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3378. var matrix = MathTmp.Matrix[0];
  3379. world.multiplyToRef(transform, matrix);
  3380. matrix.multiplyToRef(viewportMatrix, matrix);
  3381. return Vector3.TransformCoordinates(vector, matrix);
  3382. };
  3383. /**
  3384. * Unproject from screen space to object space
  3385. * @param source defines the screen space Vector3 to use
  3386. * @param viewportWidth defines the current width of the viewport
  3387. * @param viewportHeight defines the current height of the viewport
  3388. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3389. * @param transform defines the transform (view x projection) matrix to use
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3393. var matrix = MathTmp.Matrix[0];
  3394. world.multiplyToRef(transform, matrix);
  3395. matrix.invert();
  3396. source.x = source.x / viewportWidth * 2 - 1;
  3397. source.y = -(source.y / viewportHeight * 2 - 1);
  3398. var vector = Vector3.TransformCoordinates(source, matrix);
  3399. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3400. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3401. vector = vector.scale(1.0 / num);
  3402. }
  3403. return vector;
  3404. };
  3405. /**
  3406. * Unproject from screen space to object space
  3407. * @param source defines the screen space Vector3 to use
  3408. * @param viewportWidth defines the current width of the viewport
  3409. * @param viewportHeight defines the current height of the viewport
  3410. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3411. * @param view defines the view matrix to use
  3412. * @param projection defines the projection matrix to use
  3413. * @returns the new Vector3
  3414. */
  3415. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3416. var result = Vector3.Zero();
  3417. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Unproject from screen space to object space
  3422. * @param source defines the screen space Vector3 to use
  3423. * @param viewportWidth defines the current width of the viewport
  3424. * @param viewportHeight defines the current height of the viewport
  3425. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3426. * @param view defines the view matrix to use
  3427. * @param projection defines the projection matrix to use
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3431. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3432. };
  3433. /**
  3434. * Unproject from screen space to object space
  3435. * @param sourceX defines the screen space x coordinate to use
  3436. * @param sourceY defines the screen space y coordinate to use
  3437. * @param sourceZ defines the screen space z coordinate to use
  3438. * @param viewportWidth defines the current width of the viewport
  3439. * @param viewportHeight defines the current height of the viewport
  3440. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3441. * @param view defines the view matrix to use
  3442. * @param projection defines the projection matrix to use
  3443. * @param result defines the Vector3 where to store the result
  3444. */
  3445. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(view, matrix);
  3448. matrix.multiplyToRef(projection, matrix);
  3449. matrix.invert();
  3450. var screenSource = MathTmp.Vector3[0];
  3451. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3452. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3453. screenSource.z = 2 * sourceZ - 1.0;
  3454. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3455. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3456. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3457. result.scaleInPlace(1.0 / num);
  3458. }
  3459. };
  3460. /**
  3461. * Gets the minimal coordinate values between two Vector3
  3462. * @param left defines the first operand
  3463. * @param right defines the second operand
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Minimize = function (left, right) {
  3467. var min = left.clone();
  3468. min.minimizeInPlace(right);
  3469. return min;
  3470. };
  3471. /**
  3472. * Gets the maximal coordinate values between two Vector3
  3473. * @param left defines the first operand
  3474. * @param right defines the second operand
  3475. * @returns the new Vector3
  3476. */
  3477. Vector3.Maximize = function (left, right) {
  3478. var max = left.clone();
  3479. max.maximizeInPlace(right);
  3480. return max;
  3481. };
  3482. /**
  3483. * Returns the distance between the vectors "value1" and "value2"
  3484. * @param value1 defines the first operand
  3485. * @param value2 defines the second operand
  3486. * @returns the distance
  3487. */
  3488. Vector3.Distance = function (value1, value2) {
  3489. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3490. };
  3491. /**
  3492. * Returns the squared distance between the vectors "value1" and "value2"
  3493. * @param value1 defines the first operand
  3494. * @param value2 defines the second operand
  3495. * @returns the squared distance
  3496. */
  3497. Vector3.DistanceSquared = function (value1, value2) {
  3498. var x = value1.x - value2.x;
  3499. var y = value1.y - value2.y;
  3500. var z = value1.z - value2.z;
  3501. return (x * x) + (y * y) + (z * z);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 located at the center between "value1" and "value2"
  3505. * @param value1 defines the first operand
  3506. * @param value2 defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Center = function (value1, value2) {
  3510. var center = value1.add(value2);
  3511. center.scaleInPlace(0.5);
  3512. return center;
  3513. };
  3514. /**
  3515. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3516. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3517. * to something in order to rotate it from its local system to the given target system
  3518. * Note: axis1, axis2 and axis3 are normalized during this operation
  3519. * @param axis1 defines the first axis
  3520. * @param axis2 defines the second axis
  3521. * @param axis3 defines the third axis
  3522. * @returns a new Vector3
  3523. */
  3524. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3525. var rotation = Vector3.Zero();
  3526. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3527. return rotation;
  3528. };
  3529. /**
  3530. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3531. * @param axis1 defines the first axis
  3532. * @param axis2 defines the second axis
  3533. * @param axis3 defines the third axis
  3534. * @param ref defines the Vector3 where to store the result
  3535. */
  3536. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3537. var quat = MathTmp.Quaternion[0];
  3538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3539. quat.toEulerAnglesToRef(ref);
  3540. };
  3541. return Vector3;
  3542. }());
  3543. BABYLON.Vector3 = Vector3;
  3544. //Vector4 class created for EulerAngle class conversion to Quaternion
  3545. var Vector4 = /** @class */ (function () {
  3546. /**
  3547. * Creates a Vector4 object from the passed floats.
  3548. */
  3549. function Vector4(x, y, z, w) {
  3550. this.x = x;
  3551. this.y = y;
  3552. this.z = z;
  3553. this.w = w;
  3554. }
  3555. /**
  3556. * Returns the string with the Vector4 coordinates.
  3557. */
  3558. Vector4.prototype.toString = function () {
  3559. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3560. };
  3561. /**
  3562. * Returns the string "Vector4".
  3563. */
  3564. Vector4.prototype.getClassName = function () {
  3565. return "Vector4";
  3566. };
  3567. /**
  3568. * Returns the Vector4 hash code.
  3569. */
  3570. Vector4.prototype.getHashCode = function () {
  3571. var hash = this.x || 0;
  3572. hash = (hash * 397) ^ (this.y || 0);
  3573. hash = (hash * 397) ^ (this.z || 0);
  3574. hash = (hash * 397) ^ (this.w || 0);
  3575. return hash;
  3576. };
  3577. // Operators
  3578. /**
  3579. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3580. */
  3581. Vector4.prototype.asArray = function () {
  3582. var result = new Array();
  3583. this.toArray(result, 0);
  3584. return result;
  3585. };
  3586. /**
  3587. * Populates the passed array from the passed index with the Vector4 coordinates.
  3588. * Returns the Vector4.
  3589. */
  3590. Vector4.prototype.toArray = function (array, index) {
  3591. if (index === undefined) {
  3592. index = 0;
  3593. }
  3594. array[index] = this.x;
  3595. array[index + 1] = this.y;
  3596. array[index + 2] = this.z;
  3597. array[index + 3] = this.w;
  3598. return this;
  3599. };
  3600. /**
  3601. * Adds the passed vector to the current Vector4.
  3602. * Returns the updated Vector4.
  3603. */
  3604. Vector4.prototype.addInPlace = function (otherVector) {
  3605. this.x += otherVector.x;
  3606. this.y += otherVector.y;
  3607. this.z += otherVector.z;
  3608. this.w += otherVector.w;
  3609. return this;
  3610. };
  3611. /**
  3612. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3613. */
  3614. Vector4.prototype.add = function (otherVector) {
  3615. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3616. };
  3617. /**
  3618. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3619. * Returns the current Vector4.
  3620. */
  3621. Vector4.prototype.addToRef = function (otherVector, result) {
  3622. result.x = this.x + otherVector.x;
  3623. result.y = this.y + otherVector.y;
  3624. result.z = this.z + otherVector.z;
  3625. result.w = this.w + otherVector.w;
  3626. return this;
  3627. };
  3628. /**
  3629. * Subtract in place the passed vector from the current Vector4.
  3630. * Returns the updated Vector4.
  3631. */
  3632. Vector4.prototype.subtractInPlace = function (otherVector) {
  3633. this.x -= otherVector.x;
  3634. this.y -= otherVector.y;
  3635. this.z -= otherVector.z;
  3636. this.w -= otherVector.w;
  3637. return this;
  3638. };
  3639. /**
  3640. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3641. */
  3642. Vector4.prototype.subtract = function (otherVector) {
  3643. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3644. };
  3645. /**
  3646. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3647. * Returns the current Vector4.
  3648. */
  3649. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3650. result.x = this.x - otherVector.x;
  3651. result.y = this.y - otherVector.y;
  3652. result.z = this.z - otherVector.z;
  3653. result.w = this.w - otherVector.w;
  3654. return this;
  3655. };
  3656. /**
  3657. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3658. */
  3659. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3660. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3661. };
  3662. /**
  3663. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3664. * Returns the current Vector4.
  3665. */
  3666. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3667. result.x = this.x - x;
  3668. result.y = this.y - y;
  3669. result.z = this.z - z;
  3670. result.w = this.w - w;
  3671. return this;
  3672. };
  3673. /**
  3674. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3675. */
  3676. Vector4.prototype.negate = function () {
  3677. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3678. };
  3679. /**
  3680. * Multiplies the current Vector4 coordinates by scale (float).
  3681. * Returns the updated Vector4.
  3682. */
  3683. Vector4.prototype.scaleInPlace = function (scale) {
  3684. this.x *= scale;
  3685. this.y *= scale;
  3686. this.z *= scale;
  3687. this.w *= scale;
  3688. return this;
  3689. };
  3690. /**
  3691. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3692. */
  3693. Vector4.prototype.scale = function (scale) {
  3694. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3695. };
  3696. /**
  3697. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3698. * Returns the current Vector4.
  3699. */
  3700. Vector4.prototype.scaleToRef = function (scale, result) {
  3701. result.x = this.x * scale;
  3702. result.y = this.y * scale;
  3703. result.z = this.z * scale;
  3704. result.w = this.w * scale;
  3705. return this;
  3706. };
  3707. /**
  3708. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3709. */
  3710. Vector4.prototype.equals = function (otherVector) {
  3711. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3712. };
  3713. /**
  3714. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3715. */
  3716. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3717. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3718. return otherVector
  3719. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3720. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3721. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3722. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3723. };
  3724. /**
  3725. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3728. return this.x === x && this.y === y && this.z === z && this.w === w;
  3729. };
  3730. /**
  3731. * Multiplies in place the current Vector4 by the passed one.
  3732. * Returns the updated Vector4.
  3733. */
  3734. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3735. this.x *= otherVector.x;
  3736. this.y *= otherVector.y;
  3737. this.z *= otherVector.z;
  3738. this.w *= otherVector.w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3743. */
  3744. Vector4.prototype.multiply = function (otherVector) {
  3745. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3746. };
  3747. /**
  3748. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3749. * Returns the current Vector4.
  3750. */
  3751. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3752. result.x = this.x * otherVector.x;
  3753. result.y = this.y * otherVector.y;
  3754. result.z = this.z * otherVector.z;
  3755. result.w = this.w * otherVector.w;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3760. */
  3761. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3762. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3763. };
  3764. /**
  3765. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3766. */
  3767. Vector4.prototype.divide = function (otherVector) {
  3768. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3769. };
  3770. /**
  3771. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3772. * Returns the current Vector4.
  3773. */
  3774. Vector4.prototype.divideToRef = function (otherVector, result) {
  3775. result.x = this.x / otherVector.x;
  3776. result.y = this.y / otherVector.y;
  3777. result.z = this.z / otherVector.z;
  3778. result.w = this.w / otherVector.w;
  3779. return this;
  3780. };
  3781. /**
  3782. * Divides the current Vector3 coordinates by the passed ones.
  3783. * @returns the updated Vector3.
  3784. */
  3785. Vector4.prototype.divideInPlace = function (otherVector) {
  3786. return this.divideToRef(otherVector, this);
  3787. };
  3788. /**
  3789. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3790. * @param other defines the second operand
  3791. * @returns the current updated Vector4
  3792. */
  3793. Vector4.prototype.minimizeInPlace = function (other) {
  3794. if (other.x < this.x)
  3795. this.x = other.x;
  3796. if (other.y < this.y)
  3797. this.y = other.y;
  3798. if (other.z < this.z)
  3799. this.z = other.z;
  3800. if (other.w < this.w)
  3801. this.w = other.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3806. * @param other defines the second operand
  3807. * @returns the current updated Vector4
  3808. */
  3809. Vector4.prototype.maximizeInPlace = function (other) {
  3810. if (other.x > this.x)
  3811. this.x = other.x;
  3812. if (other.y > this.y)
  3813. this.y = other.y;
  3814. if (other.z > this.z)
  3815. this.z = other.z;
  3816. if (other.w > this.w)
  3817. this.w = other.w;
  3818. return this;
  3819. };
  3820. // Properties
  3821. /**
  3822. * Returns the Vector4 length (float).
  3823. */
  3824. Vector4.prototype.length = function () {
  3825. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3826. };
  3827. /**
  3828. * Returns the Vector4 squared length (float).
  3829. */
  3830. Vector4.prototype.lengthSquared = function () {
  3831. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3832. };
  3833. // Methods
  3834. /**
  3835. * Normalizes in place the Vector4.
  3836. * Returns the updated Vector4.
  3837. */
  3838. Vector4.prototype.normalize = function () {
  3839. var len = this.length();
  3840. if (len === 0)
  3841. return this;
  3842. var num = 1.0 / len;
  3843. this.x *= num;
  3844. this.y *= num;
  3845. this.z *= num;
  3846. this.w *= num;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3851. */
  3852. Vector4.prototype.toVector3 = function () {
  3853. return new Vector3(this.x, this.y, this.z);
  3854. };
  3855. /**
  3856. * Returns a new Vector4 copied from the current one.
  3857. */
  3858. Vector4.prototype.clone = function () {
  3859. return new Vector4(this.x, this.y, this.z, this.w);
  3860. };
  3861. /**
  3862. * Updates the current Vector4 with the passed one coordinates.
  3863. * Returns the updated Vector4.
  3864. */
  3865. Vector4.prototype.copyFrom = function (source) {
  3866. this.x = source.x;
  3867. this.y = source.y;
  3868. this.z = source.z;
  3869. this.w = source.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the current Vector4 coordinates with the passed floats.
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3877. this.x = x;
  3878. this.y = y;
  3879. this.z = z;
  3880. this.w = w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Updates the current Vector4 coordinates with the passed floats.
  3885. * Returns the updated Vector4.
  3886. */
  3887. Vector4.prototype.set = function (x, y, z, w) {
  3888. return this.copyFromFloats(x, y, z, w);
  3889. };
  3890. // Statics
  3891. /**
  3892. * Returns a new Vector4 set from the starting index of the passed array.
  3893. */
  3894. Vector4.FromArray = function (array, offset) {
  3895. if (!offset) {
  3896. offset = 0;
  3897. }
  3898. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3899. };
  3900. /**
  3901. * Updates the passed vector "result" from the starting index of the passed array.
  3902. */
  3903. Vector4.FromArrayToRef = function (array, offset, result) {
  3904. result.x = array[offset];
  3905. result.y = array[offset + 1];
  3906. result.z = array[offset + 2];
  3907. result.w = array[offset + 3];
  3908. };
  3909. /**
  3910. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3911. */
  3912. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3913. Vector4.FromArrayToRef(array, offset, result);
  3914. };
  3915. /**
  3916. * Updates the passed vector "result" coordinates from the passed floats.
  3917. */
  3918. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3919. result.x = x;
  3920. result.y = y;
  3921. result.z = z;
  3922. result.w = w;
  3923. };
  3924. /**
  3925. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3926. */
  3927. Vector4.Zero = function () {
  3928. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3929. };
  3930. /**
  3931. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3932. */
  3933. Vector4.One = function () {
  3934. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3935. };
  3936. /**
  3937. * Returns a new normalized Vector4 from the passed one.
  3938. */
  3939. Vector4.Normalize = function (vector) {
  3940. var result = Vector4.Zero();
  3941. Vector4.NormalizeToRef(vector, result);
  3942. return result;
  3943. };
  3944. /**
  3945. * Updates the passed vector "result" from the normalization of the passed one.
  3946. */
  3947. Vector4.NormalizeToRef = function (vector, result) {
  3948. result.copyFrom(vector);
  3949. result.normalize();
  3950. };
  3951. Vector4.Minimize = function (left, right) {
  3952. var min = left.clone();
  3953. min.minimizeInPlace(right);
  3954. return min;
  3955. };
  3956. Vector4.Maximize = function (left, right) {
  3957. var max = left.clone();
  3958. max.maximizeInPlace(right);
  3959. return max;
  3960. };
  3961. /**
  3962. * Returns the distance (float) between the vectors "value1" and "value2".
  3963. */
  3964. Vector4.Distance = function (value1, value2) {
  3965. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3966. };
  3967. /**
  3968. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3969. */
  3970. Vector4.DistanceSquared = function (value1, value2) {
  3971. var x = value1.x - value2.x;
  3972. var y = value1.y - value2.y;
  3973. var z = value1.z - value2.z;
  3974. var w = value1.w - value2.w;
  3975. return (x * x) + (y * y) + (z * z) + (w * w);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3979. */
  3980. Vector4.Center = function (value1, value2) {
  3981. var center = value1.add(value2);
  3982. center.scaleInPlace(0.5);
  3983. return center;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3987. * This methods computes transformed normalized direction vectors only.
  3988. */
  3989. Vector4.TransformNormal = function (vector, transformation) {
  3990. var result = Vector4.Zero();
  3991. Vector4.TransformNormalToRef(vector, transformation, result);
  3992. return result;
  3993. };
  3994. /**
  3995. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3996. * This methods computes transformed normalized direction vectors only.
  3997. */
  3998. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3999. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4000. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4001. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4002. result.x = x;
  4003. result.y = y;
  4004. result.z = z;
  4005. result.w = vector.w;
  4006. };
  4007. /**
  4008. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4009. * This methods computes transformed normalized direction vectors only.
  4010. */
  4011. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4012. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4013. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4014. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4015. result.w = w;
  4016. };
  4017. return Vector4;
  4018. }());
  4019. BABYLON.Vector4 = Vector4;
  4020. var Size = /** @class */ (function () {
  4021. /**
  4022. * Creates a Size object from the passed width and height (floats).
  4023. */
  4024. function Size(width, height) {
  4025. this.width = width;
  4026. this.height = height;
  4027. }
  4028. // Returns a string with the Size width and height.
  4029. Size.prototype.toString = function () {
  4030. return "{W: " + this.width + ", H: " + this.height + "}";
  4031. };
  4032. /**
  4033. * Returns the string "Size"
  4034. */
  4035. Size.prototype.getClassName = function () {
  4036. return "Size";
  4037. };
  4038. /**
  4039. * Returns the Size hash code.
  4040. */
  4041. Size.prototype.getHashCode = function () {
  4042. var hash = this.width || 0;
  4043. hash = (hash * 397) ^ (this.height || 0);
  4044. return hash;
  4045. };
  4046. /**
  4047. * Updates the current size from the passed one.
  4048. * Returns the updated Size.
  4049. */
  4050. Size.prototype.copyFrom = function (src) {
  4051. this.width = src.width;
  4052. this.height = src.height;
  4053. };
  4054. /**
  4055. * Updates in place the current Size from the passed floats.
  4056. * Returns the updated Size.
  4057. */
  4058. Size.prototype.copyFromFloats = function (width, height) {
  4059. this.width = width;
  4060. this.height = height;
  4061. return this;
  4062. };
  4063. /**
  4064. * Updates in place the current Size from the passed floats.
  4065. * Returns the updated Size.
  4066. */
  4067. Size.prototype.set = function (width, height) {
  4068. return this.copyFromFloats(width, height);
  4069. };
  4070. /**
  4071. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4072. */
  4073. Size.prototype.multiplyByFloats = function (w, h) {
  4074. return new Size(this.width * w, this.height * h);
  4075. };
  4076. /**
  4077. * Returns a new Size copied from the passed one.
  4078. */
  4079. Size.prototype.clone = function () {
  4080. return new Size(this.width, this.height);
  4081. };
  4082. /**
  4083. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4084. */
  4085. Size.prototype.equals = function (other) {
  4086. if (!other) {
  4087. return false;
  4088. }
  4089. return (this.width === other.width) && (this.height === other.height);
  4090. };
  4091. Object.defineProperty(Size.prototype, "surface", {
  4092. /**
  4093. * Returns the surface of the Size : width * height (float).
  4094. */
  4095. get: function () {
  4096. return this.width * this.height;
  4097. },
  4098. enumerable: true,
  4099. configurable: true
  4100. });
  4101. /**
  4102. * Returns a new Size set to (0.0, 0.0)
  4103. */
  4104. Size.Zero = function () {
  4105. return new Size(0.0, 0.0);
  4106. };
  4107. /**
  4108. * Returns a new Size set as the addition result of the current Size and the passed one.
  4109. */
  4110. Size.prototype.add = function (otherSize) {
  4111. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4112. return r;
  4113. };
  4114. /**
  4115. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4116. */
  4117. Size.prototype.subtract = function (otherSize) {
  4118. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4119. return r;
  4120. };
  4121. /**
  4122. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4123. */
  4124. Size.Lerp = function (start, end, amount) {
  4125. var w = start.width + ((end.width - start.width) * amount);
  4126. var h = start.height + ((end.height - start.height) * amount);
  4127. return new Size(w, h);
  4128. };
  4129. return Size;
  4130. }());
  4131. BABYLON.Size = Size;
  4132. var Quaternion = /** @class */ (function () {
  4133. /**
  4134. * Creates a new Quaternion from the passed floats.
  4135. */
  4136. function Quaternion(x, y, z, w) {
  4137. if (x === void 0) { x = 0.0; }
  4138. if (y === void 0) { y = 0.0; }
  4139. if (z === void 0) { z = 0.0; }
  4140. if (w === void 0) { w = 1.0; }
  4141. this.x = x;
  4142. this.y = y;
  4143. this.z = z;
  4144. this.w = w;
  4145. }
  4146. /**
  4147. * Returns a string with the Quaternion coordinates.
  4148. */
  4149. Quaternion.prototype.toString = function () {
  4150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4151. };
  4152. /**
  4153. * Returns the string "Quaternion".
  4154. */
  4155. Quaternion.prototype.getClassName = function () {
  4156. return "Quaternion";
  4157. };
  4158. /**
  4159. * Returns the Quaternion hash code.
  4160. */
  4161. Quaternion.prototype.getHashCode = function () {
  4162. var hash = this.x || 0;
  4163. hash = (hash * 397) ^ (this.y || 0);
  4164. hash = (hash * 397) ^ (this.z || 0);
  4165. hash = (hash * 397) ^ (this.w || 0);
  4166. return hash;
  4167. };
  4168. /**
  4169. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4170. */
  4171. Quaternion.prototype.asArray = function () {
  4172. return [this.x, this.y, this.z, this.w];
  4173. };
  4174. /**
  4175. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4176. */
  4177. Quaternion.prototype.equals = function (otherQuaternion) {
  4178. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4179. };
  4180. /**
  4181. * Returns a new Quaternion copied from the current one.
  4182. */
  4183. Quaternion.prototype.clone = function () {
  4184. return new Quaternion(this.x, this.y, this.z, this.w);
  4185. };
  4186. /**
  4187. * Updates the current Quaternion from the passed one coordinates.
  4188. * Returns the updated Quaterion.
  4189. */
  4190. Quaternion.prototype.copyFrom = function (other) {
  4191. this.x = other.x;
  4192. this.y = other.y;
  4193. this.z = other.z;
  4194. this.w = other.w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Updates the current Quaternion from the passed float coordinates.
  4199. * Returns the updated Quaterion.
  4200. */
  4201. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4202. this.x = x;
  4203. this.y = y;
  4204. this.z = z;
  4205. this.w = w;
  4206. return this;
  4207. };
  4208. /**
  4209. * Updates the current Quaternion from the passed float coordinates.
  4210. * Returns the updated Quaterion.
  4211. */
  4212. Quaternion.prototype.set = function (x, y, z, w) {
  4213. return this.copyFromFloats(x, y, z, w);
  4214. };
  4215. /**
  4216. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4217. */
  4218. Quaternion.prototype.add = function (other) {
  4219. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4220. };
  4221. /**
  4222. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4223. */
  4224. Quaternion.prototype.subtract = function (other) {
  4225. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4226. };
  4227. /**
  4228. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4229. */
  4230. Quaternion.prototype.scale = function (value) {
  4231. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4232. };
  4233. /**
  4234. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4235. */
  4236. Quaternion.prototype.multiply = function (q1) {
  4237. var result = new Quaternion(0, 0, 0, 1.0);
  4238. this.multiplyToRef(q1, result);
  4239. return result;
  4240. };
  4241. /**
  4242. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4243. * Returns the current Quaternion.
  4244. */
  4245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4250. result.copyFromFloats(x, y, z, w);
  4251. return this;
  4252. };
  4253. /**
  4254. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4255. * Returns the updated Quaternion.
  4256. */
  4257. Quaternion.prototype.multiplyInPlace = function (q1) {
  4258. this.multiplyToRef(q1, this);
  4259. return this;
  4260. };
  4261. /**
  4262. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4263. * Returns the current Quaternion.
  4264. */
  4265. Quaternion.prototype.conjugateToRef = function (ref) {
  4266. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4267. return this;
  4268. };
  4269. /**
  4270. * Conjugates in place the current Quaternion.
  4271. * Returns the updated Quaternion.
  4272. */
  4273. Quaternion.prototype.conjugateInPlace = function () {
  4274. this.x *= -1;
  4275. this.y *= -1;
  4276. this.z *= -1;
  4277. return this;
  4278. };
  4279. /**
  4280. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4281. */
  4282. Quaternion.prototype.conjugate = function () {
  4283. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4284. return result;
  4285. };
  4286. /**
  4287. * Returns the Quaternion length (float).
  4288. */
  4289. Quaternion.prototype.length = function () {
  4290. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4291. };
  4292. /**
  4293. * Normalize in place the current Quaternion.
  4294. * Returns the updated Quaternion.
  4295. */
  4296. Quaternion.prototype.normalize = function () {
  4297. var length = 1.0 / this.length();
  4298. this.x *= length;
  4299. this.y *= length;
  4300. this.z *= length;
  4301. this.w *= length;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4306. */
  4307. Quaternion.prototype.toEulerAngles = function (order) {
  4308. if (order === void 0) { order = "YZX"; }
  4309. var result = Vector3.Zero();
  4310. this.toEulerAnglesToRef(result, order);
  4311. return result;
  4312. };
  4313. /**
  4314. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4315. * Returns the current Quaternion.
  4316. */
  4317. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4318. if (order === void 0) { order = "YZX"; }
  4319. var qz = this.z;
  4320. var qx = this.x;
  4321. var qy = this.y;
  4322. var qw = this.w;
  4323. var sqw = qw * qw;
  4324. var sqz = qz * qz;
  4325. var sqx = qx * qx;
  4326. var sqy = qy * qy;
  4327. var zAxisY = qy * qz - qx * qw;
  4328. var limit = .4999999;
  4329. if (zAxisY < -limit) {
  4330. result.y = 2 * Math.atan2(qy, qw);
  4331. result.x = Math.PI / 2;
  4332. result.z = 0;
  4333. }
  4334. else if (zAxisY > limit) {
  4335. result.y = 2 * Math.atan2(qy, qw);
  4336. result.x = -Math.PI / 2;
  4337. result.z = 0;
  4338. }
  4339. else {
  4340. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4341. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4342. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4343. }
  4344. return this;
  4345. };
  4346. /**
  4347. * Updates the passed rotation matrix with the current Quaternion values.
  4348. * Returns the current Quaternion.
  4349. */
  4350. Quaternion.prototype.toRotationMatrix = function (result) {
  4351. var xx = this.x * this.x;
  4352. var yy = this.y * this.y;
  4353. var zz = this.z * this.z;
  4354. var xy = this.x * this.y;
  4355. var zw = this.z * this.w;
  4356. var zx = this.z * this.x;
  4357. var yw = this.y * this.w;
  4358. var yz = this.y * this.z;
  4359. var xw = this.x * this.w;
  4360. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4361. result.m[1] = 2.0 * (xy + zw);
  4362. result.m[2] = 2.0 * (zx - yw);
  4363. result.m[3] = 0;
  4364. result.m[4] = 2.0 * (xy - zw);
  4365. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4366. result.m[6] = 2.0 * (yz + xw);
  4367. result.m[7] = 0;
  4368. result.m[8] = 2.0 * (zx + yw);
  4369. result.m[9] = 2.0 * (yz - xw);
  4370. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4371. result.m[11] = 0;
  4372. result.m[12] = 0;
  4373. result.m[13] = 0;
  4374. result.m[14] = 0;
  4375. result.m[15] = 1.0;
  4376. result._markAsUpdated();
  4377. return this;
  4378. };
  4379. /**
  4380. * Updates the current Quaternion from the passed rotation matrix values.
  4381. * Returns the updated Quaternion.
  4382. */
  4383. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4384. Quaternion.FromRotationMatrixToRef(matrix, this);
  4385. return this;
  4386. };
  4387. // Statics
  4388. /**
  4389. * Returns a new Quaternion set from the passed rotation matrix values.
  4390. */
  4391. Quaternion.FromRotationMatrix = function (matrix) {
  4392. var result = new Quaternion();
  4393. Quaternion.FromRotationMatrixToRef(matrix, result);
  4394. return result;
  4395. };
  4396. /**
  4397. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4398. */
  4399. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4400. var data = matrix.m;
  4401. var m11 = data[0], m12 = data[4], m13 = data[8];
  4402. var m21 = data[1], m22 = data[5], m23 = data[9];
  4403. var m31 = data[2], m32 = data[6], m33 = data[10];
  4404. var trace = m11 + m22 + m33;
  4405. var s;
  4406. if (trace > 0) {
  4407. s = 0.5 / Math.sqrt(trace + 1.0);
  4408. result.w = 0.25 / s;
  4409. result.x = (m32 - m23) * s;
  4410. result.y = (m13 - m31) * s;
  4411. result.z = (m21 - m12) * s;
  4412. }
  4413. else if (m11 > m22 && m11 > m33) {
  4414. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4415. result.w = (m32 - m23) / s;
  4416. result.x = 0.25 * s;
  4417. result.y = (m12 + m21) / s;
  4418. result.z = (m13 + m31) / s;
  4419. }
  4420. else if (m22 > m33) {
  4421. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4422. result.w = (m13 - m31) / s;
  4423. result.x = (m12 + m21) / s;
  4424. result.y = 0.25 * s;
  4425. result.z = (m23 + m32) / s;
  4426. }
  4427. else {
  4428. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4429. result.w = (m21 - m12) / s;
  4430. result.x = (m13 + m31) / s;
  4431. result.y = (m23 + m32) / s;
  4432. result.z = 0.25 * s;
  4433. }
  4434. };
  4435. /**
  4436. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4437. */
  4438. Quaternion.Zero = function () {
  4439. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4440. };
  4441. /**
  4442. * Returns a new Quaternion as the inverted current Quaternion.
  4443. */
  4444. Quaternion.Inverse = function (q) {
  4445. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4446. };
  4447. /**
  4448. * Returns the identity Quaternion.
  4449. */
  4450. Quaternion.Identity = function () {
  4451. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4452. };
  4453. Quaternion.IsIdentity = function (quaternion) {
  4454. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4455. };
  4456. /**
  4457. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4458. */
  4459. Quaternion.RotationAxis = function (axis, angle) {
  4460. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4461. };
  4462. /**
  4463. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4464. */
  4465. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4466. var sin = Math.sin(angle / 2);
  4467. axis.normalize();
  4468. result.w = Math.cos(angle / 2);
  4469. result.x = axis.x * sin;
  4470. result.y = axis.y * sin;
  4471. result.z = axis.z * sin;
  4472. return result;
  4473. };
  4474. /**
  4475. * Retuns a new Quaternion set from the starting index of the passed array.
  4476. */
  4477. Quaternion.FromArray = function (array, offset) {
  4478. if (!offset) {
  4479. offset = 0;
  4480. }
  4481. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4482. };
  4483. /**
  4484. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4485. */
  4486. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4487. var q = new Quaternion();
  4488. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4489. return q;
  4490. };
  4491. /**
  4492. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4493. */
  4494. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4495. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4496. var halfRoll = roll * 0.5;
  4497. var halfPitch = pitch * 0.5;
  4498. var halfYaw = yaw * 0.5;
  4499. var sinRoll = Math.sin(halfRoll);
  4500. var cosRoll = Math.cos(halfRoll);
  4501. var sinPitch = Math.sin(halfPitch);
  4502. var cosPitch = Math.cos(halfPitch);
  4503. var sinYaw = Math.sin(halfYaw);
  4504. var cosYaw = Math.cos(halfYaw);
  4505. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4506. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4507. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4508. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4509. };
  4510. /**
  4511. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4512. */
  4513. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4514. var result = new Quaternion();
  4515. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4520. */
  4521. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4522. // Produces a quaternion from Euler angles in the z-x-z orientation
  4523. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4524. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4525. var halfBeta = beta * 0.5;
  4526. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4527. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4528. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4529. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4530. };
  4531. /**
  4532. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4533. * cf to Vector3.RotationFromAxis() documentation.
  4534. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4535. */
  4536. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4537. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4539. return quat;
  4540. };
  4541. /**
  4542. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4543. * cf to Vector3.RotationFromAxis() documentation.
  4544. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4545. */
  4546. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4547. var rotMat = MathTmp.Matrix[0];
  4548. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4549. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4550. };
  4551. Quaternion.Slerp = function (left, right, amount) {
  4552. var result = Quaternion.Identity();
  4553. Quaternion.SlerpToRef(left, right, amount, result);
  4554. return result;
  4555. };
  4556. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4557. var num2;
  4558. var num3;
  4559. var num = amount;
  4560. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4561. var flag = false;
  4562. if (num4 < 0) {
  4563. flag = true;
  4564. num4 = -num4;
  4565. }
  4566. if (num4 > 0.999999) {
  4567. num3 = 1 - num;
  4568. num2 = flag ? -num : num;
  4569. }
  4570. else {
  4571. var num5 = Math.acos(num4);
  4572. var num6 = (1.0 / Math.sin(num5));
  4573. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4574. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4575. }
  4576. result.x = (num3 * left.x) + (num2 * right.x);
  4577. result.y = (num3 * left.y) + (num2 * right.y);
  4578. result.z = (num3 * left.z) + (num2 * right.z);
  4579. result.w = (num3 * left.w) + (num2 * right.w);
  4580. };
  4581. /**
  4582. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4583. */
  4584. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4585. var squared = amount * amount;
  4586. var cubed = amount * squared;
  4587. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4588. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4589. var part3 = (cubed - (2.0 * squared)) + amount;
  4590. var part4 = cubed - squared;
  4591. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4592. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4593. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4594. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4595. return new Quaternion(x, y, z, w);
  4596. };
  4597. return Quaternion;
  4598. }());
  4599. BABYLON.Quaternion = Quaternion;
  4600. var Matrix = /** @class */ (function () {
  4601. function Matrix() {
  4602. this._isIdentity = false;
  4603. this._isIdentityDirty = true;
  4604. this.m = new Float32Array(16);
  4605. this._markAsUpdated();
  4606. }
  4607. Matrix.prototype._markAsUpdated = function () {
  4608. this.updateFlag = Matrix._updateFlagSeed++;
  4609. this._isIdentityDirty = true;
  4610. };
  4611. // Properties
  4612. /**
  4613. * Boolean : True is the matrix is the identity matrix
  4614. */
  4615. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4616. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4617. if (this._isIdentityDirty) {
  4618. this._isIdentityDirty = false;
  4619. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4620. this._isIdentity = false;
  4621. }
  4622. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4623. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4624. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4625. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4626. this._isIdentity = false;
  4627. }
  4628. else {
  4629. this._isIdentity = true;
  4630. }
  4631. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4632. this._isIdentity = false;
  4633. }
  4634. }
  4635. return this._isIdentity;
  4636. };
  4637. /**
  4638. * Returns the matrix determinant (float).
  4639. */
  4640. Matrix.prototype.determinant = function () {
  4641. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4642. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4643. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4644. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4645. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4646. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4647. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4648. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4649. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4650. };
  4651. // Methods
  4652. /**
  4653. * Returns the matrix underlying array.
  4654. */
  4655. Matrix.prototype.toArray = function () {
  4656. return this.m;
  4657. };
  4658. /**
  4659. * Returns the matrix underlying array.
  4660. */
  4661. Matrix.prototype.asArray = function () {
  4662. return this.toArray();
  4663. };
  4664. /**
  4665. * Inverts in place the Matrix.
  4666. * Returns the Matrix inverted.
  4667. */
  4668. Matrix.prototype.invert = function () {
  4669. this.invertToRef(this);
  4670. return this;
  4671. };
  4672. /**
  4673. * Sets all the matrix elements to zero.
  4674. * Returns the Matrix.
  4675. */
  4676. Matrix.prototype.reset = function () {
  4677. for (var index = 0; index < 16; index++) {
  4678. this.m[index] = 0.0;
  4679. }
  4680. this._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4685. */
  4686. Matrix.prototype.add = function (other) {
  4687. var result = new Matrix();
  4688. this.addToRef(other, result);
  4689. return result;
  4690. };
  4691. /**
  4692. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4693. * Returns the Matrix.
  4694. */
  4695. Matrix.prototype.addToRef = function (other, result) {
  4696. for (var index = 0; index < 16; index++) {
  4697. result.m[index] = this.m[index] + other.m[index];
  4698. }
  4699. result._markAsUpdated();
  4700. return this;
  4701. };
  4702. /**
  4703. * Adds in place the passed matrix to the current Matrix.
  4704. * Returns the updated Matrix.
  4705. */
  4706. Matrix.prototype.addToSelf = function (other) {
  4707. for (var index = 0; index < 16; index++) {
  4708. this.m[index] += other.m[index];
  4709. }
  4710. this._markAsUpdated();
  4711. return this;
  4712. };
  4713. /**
  4714. * Sets the passed matrix with the current inverted Matrix.
  4715. * Returns the unmodified current Matrix.
  4716. */
  4717. Matrix.prototype.invertToRef = function (other) {
  4718. var l1 = this.m[0];
  4719. var l2 = this.m[1];
  4720. var l3 = this.m[2];
  4721. var l4 = this.m[3];
  4722. var l5 = this.m[4];
  4723. var l6 = this.m[5];
  4724. var l7 = this.m[6];
  4725. var l8 = this.m[7];
  4726. var l9 = this.m[8];
  4727. var l10 = this.m[9];
  4728. var l11 = this.m[10];
  4729. var l12 = this.m[11];
  4730. var l13 = this.m[12];
  4731. var l14 = this.m[13];
  4732. var l15 = this.m[14];
  4733. var l16 = this.m[15];
  4734. var l17 = (l11 * l16) - (l12 * l15);
  4735. var l18 = (l10 * l16) - (l12 * l14);
  4736. var l19 = (l10 * l15) - (l11 * l14);
  4737. var l20 = (l9 * l16) - (l12 * l13);
  4738. var l21 = (l9 * l15) - (l11 * l13);
  4739. var l22 = (l9 * l14) - (l10 * l13);
  4740. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4741. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4742. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4743. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4744. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4745. var l28 = (l7 * l16) - (l8 * l15);
  4746. var l29 = (l6 * l16) - (l8 * l14);
  4747. var l30 = (l6 * l15) - (l7 * l14);
  4748. var l31 = (l5 * l16) - (l8 * l13);
  4749. var l32 = (l5 * l15) - (l7 * l13);
  4750. var l33 = (l5 * l14) - (l6 * l13);
  4751. var l34 = (l7 * l12) - (l8 * l11);
  4752. var l35 = (l6 * l12) - (l8 * l10);
  4753. var l36 = (l6 * l11) - (l7 * l10);
  4754. var l37 = (l5 * l12) - (l8 * l9);
  4755. var l38 = (l5 * l11) - (l7 * l9);
  4756. var l39 = (l5 * l10) - (l6 * l9);
  4757. other.m[0] = l23 * l27;
  4758. other.m[4] = l24 * l27;
  4759. other.m[8] = l25 * l27;
  4760. other.m[12] = l26 * l27;
  4761. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4762. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4763. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4764. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4765. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4766. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4767. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4768. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4769. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4770. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4771. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4772. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4773. other._markAsUpdated();
  4774. return this;
  4775. };
  4776. /**
  4777. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4778. * Returns the updated Matrix.
  4779. */
  4780. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4781. this.m[12] = x;
  4782. this.m[13] = y;
  4783. this.m[14] = z;
  4784. this._markAsUpdated();
  4785. return this;
  4786. };
  4787. /**
  4788. * Inserts the translation vector in the current Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.setTranslation = function (vector3) {
  4792. this.m[12] = vector3.x;
  4793. this.m[13] = vector3.y;
  4794. this.m[14] = vector3.z;
  4795. this._markAsUpdated();
  4796. return this;
  4797. };
  4798. /**
  4799. * Returns a new Vector3 as the extracted translation from the Matrix.
  4800. */
  4801. Matrix.prototype.getTranslation = function () {
  4802. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4803. };
  4804. /**
  4805. * Fill a Vector3 with the extracted translation from the Matrix.
  4806. */
  4807. Matrix.prototype.getTranslationToRef = function (result) {
  4808. result.x = this.m[12];
  4809. result.y = this.m[13];
  4810. result.z = this.m[14];
  4811. return this;
  4812. };
  4813. /**
  4814. * Remove rotation and scaling part from the Matrix.
  4815. * Returns the updated Matrix.
  4816. */
  4817. Matrix.prototype.removeRotationAndScaling = function () {
  4818. this.setRowFromFloats(0, 1, 0, 0, 0);
  4819. this.setRowFromFloats(1, 0, 1, 0, 0);
  4820. this.setRowFromFloats(2, 0, 0, 1, 0);
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4825. */
  4826. Matrix.prototype.multiply = function (other) {
  4827. var result = new Matrix();
  4828. this.multiplyToRef(other, result);
  4829. return result;
  4830. };
  4831. /**
  4832. * Updates the current Matrix from the passed one values.
  4833. * Returns the updated Matrix.
  4834. */
  4835. Matrix.prototype.copyFrom = function (other) {
  4836. for (var index = 0; index < 16; index++) {
  4837. this.m[index] = other.m[index];
  4838. }
  4839. this._markAsUpdated();
  4840. return this;
  4841. };
  4842. /**
  4843. * Populates the passed array from the starting index with the Matrix values.
  4844. * Returns the Matrix.
  4845. */
  4846. Matrix.prototype.copyToArray = function (array, offset) {
  4847. if (offset === void 0) { offset = 0; }
  4848. for (var index = 0; index < 16; index++) {
  4849. array[offset + index] = this.m[index];
  4850. }
  4851. return this;
  4852. };
  4853. /**
  4854. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4855. */
  4856. Matrix.prototype.multiplyToRef = function (other, result) {
  4857. this.multiplyToArray(other, result.m, 0);
  4858. result._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4863. */
  4864. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4865. var tm0 = this.m[0];
  4866. var tm1 = this.m[1];
  4867. var tm2 = this.m[2];
  4868. var tm3 = this.m[3];
  4869. var tm4 = this.m[4];
  4870. var tm5 = this.m[5];
  4871. var tm6 = this.m[6];
  4872. var tm7 = this.m[7];
  4873. var tm8 = this.m[8];
  4874. var tm9 = this.m[9];
  4875. var tm10 = this.m[10];
  4876. var tm11 = this.m[11];
  4877. var tm12 = this.m[12];
  4878. var tm13 = this.m[13];
  4879. var tm14 = this.m[14];
  4880. var tm15 = this.m[15];
  4881. var om0 = other.m[0];
  4882. var om1 = other.m[1];
  4883. var om2 = other.m[2];
  4884. var om3 = other.m[3];
  4885. var om4 = other.m[4];
  4886. var om5 = other.m[5];
  4887. var om6 = other.m[6];
  4888. var om7 = other.m[7];
  4889. var om8 = other.m[8];
  4890. var om9 = other.m[9];
  4891. var om10 = other.m[10];
  4892. var om11 = other.m[11];
  4893. var om12 = other.m[12];
  4894. var om13 = other.m[13];
  4895. var om14 = other.m[14];
  4896. var om15 = other.m[15];
  4897. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4898. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4899. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4900. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4901. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4902. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4903. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4904. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4905. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4906. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4907. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4908. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4909. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4910. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4911. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4912. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4913. return this;
  4914. };
  4915. /**
  4916. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4917. */
  4918. Matrix.prototype.equals = function (value) {
  4919. return value &&
  4920. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4921. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4922. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4923. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4924. };
  4925. /**
  4926. * Returns a new Matrix from the current Matrix.
  4927. */
  4928. Matrix.prototype.clone = function () {
  4929. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4930. };
  4931. /**
  4932. * Returns the string "Matrix"
  4933. */
  4934. Matrix.prototype.getClassName = function () {
  4935. return "Matrix";
  4936. };
  4937. /**
  4938. * Returns the Matrix hash code.
  4939. */
  4940. Matrix.prototype.getHashCode = function () {
  4941. var hash = this.m[0] || 0;
  4942. for (var i = 1; i < 16; i++) {
  4943. hash = (hash * 397) ^ (this.m[i] || 0);
  4944. }
  4945. return hash;
  4946. };
  4947. /**
  4948. * Decomposes the current Matrix into :
  4949. * - a scale vector3 passed as a reference to update,
  4950. * - a rotation quaternion passed as a reference to update,
  4951. * - a translation vector3 passed as a reference to update.
  4952. * Returns the true if operation was successful.
  4953. */
  4954. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4955. translation.x = this.m[12];
  4956. translation.y = this.m[13];
  4957. translation.z = this.m[14];
  4958. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4959. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4960. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4961. if (this.determinant() <= 0) {
  4962. scale.y *= -1;
  4963. }
  4964. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4965. rotation.x = 0;
  4966. rotation.y = 0;
  4967. rotation.z = 0;
  4968. rotation.w = 1;
  4969. return false;
  4970. }
  4971. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4972. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4973. return true;
  4974. };
  4975. /**
  4976. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4977. * @param ref matrix to store the result
  4978. */
  4979. Matrix.prototype.toNormalMatrix = function (ref) {
  4980. this.invertToRef(ref);
  4981. ref.transpose();
  4982. var m = ref.m;
  4983. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  4984. };
  4985. /**
  4986. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4987. */
  4988. Matrix.prototype.getRotationMatrix = function () {
  4989. var result = Matrix.Identity();
  4990. this.getRotationMatrixToRef(result);
  4991. return result;
  4992. };
  4993. /**
  4994. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4995. * Returns the current Matrix.
  4996. */
  4997. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4998. var m = this.m;
  4999. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5000. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5001. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5002. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5003. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5004. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5005. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5006. return this;
  5007. };
  5008. // Statics
  5009. /**
  5010. * Returns a new Matrix set from the starting index of the passed array.
  5011. */
  5012. Matrix.FromArray = function (array, offset) {
  5013. var result = new Matrix();
  5014. if (!offset) {
  5015. offset = 0;
  5016. }
  5017. Matrix.FromArrayToRef(array, offset, result);
  5018. return result;
  5019. };
  5020. /**
  5021. * Sets the passed "result" matrix from the starting index of the passed array.
  5022. */
  5023. Matrix.FromArrayToRef = function (array, offset, result) {
  5024. for (var index = 0; index < 16; index++) {
  5025. result.m[index] = array[index + offset];
  5026. }
  5027. result._markAsUpdated();
  5028. };
  5029. /**
  5030. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5031. */
  5032. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5033. for (var index = 0; index < 16; index++) {
  5034. result.m[index] = array[index + offset] * scale;
  5035. }
  5036. result._markAsUpdated();
  5037. };
  5038. /**
  5039. * Sets the passed matrix "result" with the 16 passed floats.
  5040. */
  5041. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5042. result.m[0] = initialM11;
  5043. result.m[1] = initialM12;
  5044. result.m[2] = initialM13;
  5045. result.m[3] = initialM14;
  5046. result.m[4] = initialM21;
  5047. result.m[5] = initialM22;
  5048. result.m[6] = initialM23;
  5049. result.m[7] = initialM24;
  5050. result.m[8] = initialM31;
  5051. result.m[9] = initialM32;
  5052. result.m[10] = initialM33;
  5053. result.m[11] = initialM34;
  5054. result.m[12] = initialM41;
  5055. result.m[13] = initialM42;
  5056. result.m[14] = initialM43;
  5057. result.m[15] = initialM44;
  5058. result._markAsUpdated();
  5059. };
  5060. /**
  5061. * Returns the index-th row of the current matrix as a new Vector4.
  5062. */
  5063. Matrix.prototype.getRow = function (index) {
  5064. if (index < 0 || index > 3) {
  5065. return null;
  5066. }
  5067. var i = index * 4;
  5068. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5069. };
  5070. /**
  5071. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5072. * Returns the updated Matrix.
  5073. */
  5074. Matrix.prototype.setRow = function (index, row) {
  5075. if (index < 0 || index > 3) {
  5076. return this;
  5077. }
  5078. var i = index * 4;
  5079. this.m[i + 0] = row.x;
  5080. this.m[i + 1] = row.y;
  5081. this.m[i + 2] = row.z;
  5082. this.m[i + 3] = row.w;
  5083. this._markAsUpdated();
  5084. return this;
  5085. };
  5086. /**
  5087. * Compute the transpose of the matrix.
  5088. * Returns a new Matrix.
  5089. */
  5090. Matrix.prototype.transpose = function () {
  5091. return Matrix.Transpose(this);
  5092. };
  5093. /**
  5094. * Compute the transpose of the matrix.
  5095. * Returns the current matrix.
  5096. */
  5097. Matrix.prototype.transposeToRef = function (result) {
  5098. Matrix.TransposeToRef(this, result);
  5099. return this;
  5100. };
  5101. /**
  5102. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5103. * Returns the updated Matrix.
  5104. */
  5105. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5106. if (index < 0 || index > 3) {
  5107. return this;
  5108. }
  5109. var i = index * 4;
  5110. this.m[i + 0] = x;
  5111. this.m[i + 1] = y;
  5112. this.m[i + 2] = z;
  5113. this.m[i + 3] = w;
  5114. this._markAsUpdated();
  5115. return this;
  5116. };
  5117. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5118. /**
  5119. * Static identity matrix to be used as readonly matrix
  5120. * Must not be updated.
  5121. */
  5122. get: function () {
  5123. return Matrix._identityReadOnly;
  5124. },
  5125. enumerable: true,
  5126. configurable: true
  5127. });
  5128. /**
  5129. * Returns a new Matrix set from the 16 passed floats.
  5130. */
  5131. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5132. var result = new Matrix();
  5133. result.m[0] = initialM11;
  5134. result.m[1] = initialM12;
  5135. result.m[2] = initialM13;
  5136. result.m[3] = initialM14;
  5137. result.m[4] = initialM21;
  5138. result.m[5] = initialM22;
  5139. result.m[6] = initialM23;
  5140. result.m[7] = initialM24;
  5141. result.m[8] = initialM31;
  5142. result.m[9] = initialM32;
  5143. result.m[10] = initialM33;
  5144. result.m[11] = initialM34;
  5145. result.m[12] = initialM41;
  5146. result.m[13] = initialM42;
  5147. result.m[14] = initialM43;
  5148. result.m[15] = initialM44;
  5149. return result;
  5150. };
  5151. /**
  5152. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5153. */
  5154. Matrix.Compose = function (scale, rotation, translation) {
  5155. var result = Matrix.Identity();
  5156. Matrix.ComposeToRef(scale, rotation, translation, result);
  5157. return result;
  5158. };
  5159. /**
  5160. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5161. */
  5162. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5163. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5164. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5165. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5166. result.setTranslation(translation);
  5167. };
  5168. /**
  5169. * Returns a new indentity Matrix.
  5170. */
  5171. Matrix.Identity = function () {
  5172. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5173. };
  5174. /**
  5175. * Sets the passed "result" as an identity matrix.
  5176. */
  5177. Matrix.IdentityToRef = function (result) {
  5178. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5179. };
  5180. /**
  5181. * Returns a new zero Matrix.
  5182. */
  5183. Matrix.Zero = function () {
  5184. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5185. };
  5186. /**
  5187. * Returns a new rotation matrix for "angle" radians around the X axis.
  5188. */
  5189. Matrix.RotationX = function (angle) {
  5190. var result = new Matrix();
  5191. Matrix.RotationXToRef(angle, result);
  5192. return result;
  5193. };
  5194. /**
  5195. * Returns a new Matrix as the passed inverted one.
  5196. */
  5197. Matrix.Invert = function (source) {
  5198. var result = new Matrix();
  5199. source.invertToRef(result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5204. */
  5205. Matrix.RotationXToRef = function (angle, result) {
  5206. var s = Math.sin(angle);
  5207. var c = Math.cos(angle);
  5208. result.m[0] = 1.0;
  5209. result.m[15] = 1.0;
  5210. result.m[5] = c;
  5211. result.m[10] = c;
  5212. result.m[9] = -s;
  5213. result.m[6] = s;
  5214. result.m[1] = 0.0;
  5215. result.m[2] = 0.0;
  5216. result.m[3] = 0.0;
  5217. result.m[4] = 0.0;
  5218. result.m[7] = 0.0;
  5219. result.m[8] = 0.0;
  5220. result.m[11] = 0.0;
  5221. result.m[12] = 0.0;
  5222. result.m[13] = 0.0;
  5223. result.m[14] = 0.0;
  5224. result._markAsUpdated();
  5225. };
  5226. /**
  5227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5228. */
  5229. Matrix.RotationY = function (angle) {
  5230. var result = new Matrix();
  5231. Matrix.RotationYToRef(angle, result);
  5232. return result;
  5233. };
  5234. /**
  5235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5236. */
  5237. Matrix.RotationYToRef = function (angle, result) {
  5238. var s = Math.sin(angle);
  5239. var c = Math.cos(angle);
  5240. result.m[5] = 1.0;
  5241. result.m[15] = 1.0;
  5242. result.m[0] = c;
  5243. result.m[2] = -s;
  5244. result.m[8] = s;
  5245. result.m[10] = c;
  5246. result.m[1] = 0.0;
  5247. result.m[3] = 0.0;
  5248. result.m[4] = 0.0;
  5249. result.m[6] = 0.0;
  5250. result.m[7] = 0.0;
  5251. result.m[9] = 0.0;
  5252. result.m[11] = 0.0;
  5253. result.m[12] = 0.0;
  5254. result.m[13] = 0.0;
  5255. result.m[14] = 0.0;
  5256. result._markAsUpdated();
  5257. };
  5258. /**
  5259. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5260. */
  5261. Matrix.RotationZ = function (angle) {
  5262. var result = new Matrix();
  5263. Matrix.RotationZToRef(angle, result);
  5264. return result;
  5265. };
  5266. /**
  5267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5268. */
  5269. Matrix.RotationZToRef = function (angle, result) {
  5270. var s = Math.sin(angle);
  5271. var c = Math.cos(angle);
  5272. result.m[10] = 1.0;
  5273. result.m[15] = 1.0;
  5274. result.m[0] = c;
  5275. result.m[1] = s;
  5276. result.m[4] = -s;
  5277. result.m[5] = c;
  5278. result.m[2] = 0.0;
  5279. result.m[3] = 0.0;
  5280. result.m[6] = 0.0;
  5281. result.m[7] = 0.0;
  5282. result.m[8] = 0.0;
  5283. result.m[9] = 0.0;
  5284. result.m[11] = 0.0;
  5285. result.m[12] = 0.0;
  5286. result.m[13] = 0.0;
  5287. result.m[14] = 0.0;
  5288. result._markAsUpdated();
  5289. };
  5290. /**
  5291. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5292. */
  5293. Matrix.RotationAxis = function (axis, angle) {
  5294. var result = Matrix.Zero();
  5295. Matrix.RotationAxisToRef(axis, angle, result);
  5296. return result;
  5297. };
  5298. /**
  5299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5300. */
  5301. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5302. var s = Math.sin(-angle);
  5303. var c = Math.cos(-angle);
  5304. var c1 = 1 - c;
  5305. axis.normalize();
  5306. result.m[0] = (axis.x * axis.x) * c1 + c;
  5307. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5308. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5309. result.m[3] = 0.0;
  5310. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5311. result.m[5] = (axis.y * axis.y) * c1 + c;
  5312. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5313. result.m[7] = 0.0;
  5314. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5315. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5316. result.m[10] = (axis.z * axis.z) * c1 + c;
  5317. result.m[11] = 0.0;
  5318. result.m[15] = 1.0;
  5319. result._markAsUpdated();
  5320. };
  5321. /**
  5322. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5323. */
  5324. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5325. var result = new Matrix();
  5326. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5327. return result;
  5328. };
  5329. /**
  5330. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5331. */
  5332. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5333. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5334. this._tempQuaternion.toRotationMatrix(result);
  5335. };
  5336. /**
  5337. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5338. */
  5339. Matrix.Scaling = function (x, y, z) {
  5340. var result = Matrix.Zero();
  5341. Matrix.ScalingToRef(x, y, z, result);
  5342. return result;
  5343. };
  5344. /**
  5345. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5346. */
  5347. Matrix.ScalingToRef = function (x, y, z, result) {
  5348. result.m[0] = x;
  5349. result.m[1] = 0.0;
  5350. result.m[2] = 0.0;
  5351. result.m[3] = 0.0;
  5352. result.m[4] = 0.0;
  5353. result.m[5] = y;
  5354. result.m[6] = 0.0;
  5355. result.m[7] = 0.0;
  5356. result.m[8] = 0.0;
  5357. result.m[9] = 0.0;
  5358. result.m[10] = z;
  5359. result.m[11] = 0.0;
  5360. result.m[12] = 0.0;
  5361. result.m[13] = 0.0;
  5362. result.m[14] = 0.0;
  5363. result.m[15] = 1.0;
  5364. result._markAsUpdated();
  5365. };
  5366. /**
  5367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5368. */
  5369. Matrix.Translation = function (x, y, z) {
  5370. var result = Matrix.Identity();
  5371. Matrix.TranslationToRef(x, y, z, result);
  5372. return result;
  5373. };
  5374. /**
  5375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5376. */
  5377. Matrix.TranslationToRef = function (x, y, z, result) {
  5378. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5379. };
  5380. /**
  5381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5382. */
  5383. Matrix.Lerp = function (startValue, endValue, gradient) {
  5384. var result = Matrix.Zero();
  5385. for (var index = 0; index < 16; index++) {
  5386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5387. }
  5388. result._markAsUpdated();
  5389. return result;
  5390. };
  5391. /**
  5392. * Returns a new Matrix whose values are computed by :
  5393. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5394. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5395. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5396. */
  5397. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5398. var startScale = new Vector3(0, 0, 0);
  5399. var startRotation = new Quaternion();
  5400. var startTranslation = new Vector3(0, 0, 0);
  5401. startValue.decompose(startScale, startRotation, startTranslation);
  5402. var endScale = new Vector3(0, 0, 0);
  5403. var endRotation = new Quaternion();
  5404. var endTranslation = new Vector3(0, 0, 0);
  5405. endValue.decompose(endScale, endRotation, endTranslation);
  5406. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5407. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5408. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5409. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5410. };
  5411. /**
  5412. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5413. * This methods works for a Left-Handed system.
  5414. */
  5415. Matrix.LookAtLH = function (eye, target, up) {
  5416. var result = Matrix.Zero();
  5417. Matrix.LookAtLHToRef(eye, target, up, result);
  5418. return result;
  5419. };
  5420. /**
  5421. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5422. * This methods works for a Left-Handed system.
  5423. */
  5424. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5425. // Z axis
  5426. target.subtractToRef(eye, this._zAxis);
  5427. this._zAxis.normalize();
  5428. // X axis
  5429. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5430. if (this._xAxis.lengthSquared() === 0) {
  5431. this._xAxis.x = 1.0;
  5432. }
  5433. else {
  5434. this._xAxis.normalize();
  5435. }
  5436. // Y axis
  5437. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5438. this._yAxis.normalize();
  5439. // Eye angles
  5440. var ex = -Vector3.Dot(this._xAxis, eye);
  5441. var ey = -Vector3.Dot(this._yAxis, eye);
  5442. var ez = -Vector3.Dot(this._zAxis, eye);
  5443. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5444. };
  5445. /**
  5446. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5447. * This methods works for a Right-Handed system.
  5448. */
  5449. Matrix.LookAtRH = function (eye, target, up) {
  5450. var result = Matrix.Zero();
  5451. Matrix.LookAtRHToRef(eye, target, up, result);
  5452. return result;
  5453. };
  5454. /**
  5455. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5456. * This methods works for a Left-Handed system.
  5457. */
  5458. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5459. // Z axis
  5460. eye.subtractToRef(target, this._zAxis);
  5461. this._zAxis.normalize();
  5462. // X axis
  5463. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5464. if (this._xAxis.lengthSquared() === 0) {
  5465. this._xAxis.x = 1.0;
  5466. }
  5467. else {
  5468. this._xAxis.normalize();
  5469. }
  5470. // Y axis
  5471. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5472. this._yAxis.normalize();
  5473. // Eye angles
  5474. var ex = -Vector3.Dot(this._xAxis, eye);
  5475. var ey = -Vector3.Dot(this._yAxis, eye);
  5476. var ez = -Vector3.Dot(this._zAxis, eye);
  5477. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5478. };
  5479. /**
  5480. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5481. */
  5482. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5483. var matrix = Matrix.Zero();
  5484. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5485. return matrix;
  5486. };
  5487. /**
  5488. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5489. */
  5490. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5491. var n = znear;
  5492. var f = zfar;
  5493. var a = 2.0 / width;
  5494. var b = 2.0 / height;
  5495. var c = 2.0 / (f - n);
  5496. var d = -(f + n) / (f - n);
  5497. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5498. };
  5499. /**
  5500. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5501. */
  5502. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5503. var matrix = Matrix.Zero();
  5504. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5505. return matrix;
  5506. };
  5507. /**
  5508. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5509. */
  5510. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5511. var n = znear;
  5512. var f = zfar;
  5513. var a = 2.0 / (right - left);
  5514. var b = 2.0 / (top - bottom);
  5515. var c = 2.0 / (f - n);
  5516. var d = -(f + n) / (f - n);
  5517. var i0 = (left + right) / (left - right);
  5518. var i1 = (top + bottom) / (bottom - top);
  5519. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5520. };
  5521. /**
  5522. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5523. */
  5524. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5525. var matrix = Matrix.Zero();
  5526. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5527. return matrix;
  5528. };
  5529. /**
  5530. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5531. */
  5532. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5533. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5534. result.m[10] *= -1.0;
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5538. */
  5539. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. var n = znear;
  5542. var f = zfar;
  5543. var a = 2.0 * n / width;
  5544. var b = 2.0 * n / height;
  5545. var c = (f + n) / (f - n);
  5546. var d = -2.0 * f * n / (f - n);
  5547. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5548. return matrix;
  5549. };
  5550. /**
  5551. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5552. */
  5553. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5556. return matrix;
  5557. };
  5558. /**
  5559. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5560. */
  5561. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5562. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5563. var n = znear;
  5564. var f = zfar;
  5565. var t = 1.0 / (Math.tan(fov * 0.5));
  5566. var a = isVerticalFovFixed ? (t / aspect) : t;
  5567. var b = isVerticalFovFixed ? t : (t * aspect);
  5568. var c = (f + n) / (f - n);
  5569. var d = -2.0 * f * n / (f - n);
  5570. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5571. };
  5572. /**
  5573. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5574. */
  5575. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5576. var matrix = Matrix.Zero();
  5577. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5578. return matrix;
  5579. };
  5580. /**
  5581. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5582. */
  5583. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5584. //alternatively this could be expressed as:
  5585. // m = PerspectiveFovLHToRef
  5586. // m[10] *= -1.0;
  5587. // m[11] *= -1.0;
  5588. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5589. var n = znear;
  5590. var f = zfar;
  5591. var t = 1.0 / (Math.tan(fov * 0.5));
  5592. var a = isVerticalFovFixed ? (t / aspect) : t;
  5593. var b = isVerticalFovFixed ? t : (t * aspect);
  5594. var c = -(f + n) / (f - n);
  5595. var d = -2 * f * n / (f - n);
  5596. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5597. };
  5598. /**
  5599. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5600. */
  5601. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5602. if (rightHanded === void 0) { rightHanded = false; }
  5603. var rightHandedFactor = rightHanded ? -1 : 1;
  5604. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5605. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5606. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5607. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5608. var xScale = 2.0 / (leftTan + rightTan);
  5609. var yScale = 2.0 / (upTan + downTan);
  5610. result.m[0] = xScale;
  5611. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5612. result.m[5] = yScale;
  5613. result.m[6] = result.m[7] = 0.0;
  5614. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5615. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5616. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5617. result.m[10] = -zfar / (znear - zfar);
  5618. result.m[11] = 1.0 * rightHandedFactor;
  5619. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5620. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5621. // result.m[14] = (znear * zfar) / (znear - zfar);
  5622. result._markAsUpdated();
  5623. };
  5624. /**
  5625. * Returns the final transformation matrix : world * view * projection * viewport
  5626. */
  5627. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5628. var cw = viewport.width;
  5629. var ch = viewport.height;
  5630. var cx = viewport.x;
  5631. var cy = viewport.y;
  5632. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5633. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5634. };
  5635. /**
  5636. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5637. */
  5638. Matrix.GetAsMatrix2x2 = function (matrix) {
  5639. return new Float32Array([
  5640. matrix.m[0], matrix.m[1],
  5641. matrix.m[4], matrix.m[5]
  5642. ]);
  5643. };
  5644. /**
  5645. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5646. */
  5647. Matrix.GetAsMatrix3x3 = function (matrix) {
  5648. return new Float32Array([
  5649. matrix.m[0], matrix.m[1], matrix.m[2],
  5650. matrix.m[4], matrix.m[5], matrix.m[6],
  5651. matrix.m[8], matrix.m[9], matrix.m[10]
  5652. ]);
  5653. };
  5654. /**
  5655. * Compute the transpose of the passed Matrix.
  5656. * Returns a new Matrix.
  5657. */
  5658. Matrix.Transpose = function (matrix) {
  5659. var result = new Matrix();
  5660. Matrix.TransposeToRef(matrix, result);
  5661. return result;
  5662. };
  5663. /**
  5664. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5665. */
  5666. Matrix.TransposeToRef = function (matrix, result) {
  5667. result.m[0] = matrix.m[0];
  5668. result.m[1] = matrix.m[4];
  5669. result.m[2] = matrix.m[8];
  5670. result.m[3] = matrix.m[12];
  5671. result.m[4] = matrix.m[1];
  5672. result.m[5] = matrix.m[5];
  5673. result.m[6] = matrix.m[9];
  5674. result.m[7] = matrix.m[13];
  5675. result.m[8] = matrix.m[2];
  5676. result.m[9] = matrix.m[6];
  5677. result.m[10] = matrix.m[10];
  5678. result.m[11] = matrix.m[14];
  5679. result.m[12] = matrix.m[3];
  5680. result.m[13] = matrix.m[7];
  5681. result.m[14] = matrix.m[11];
  5682. result.m[15] = matrix.m[15];
  5683. };
  5684. /**
  5685. * Returns a new Matrix as the reflection matrix across the passed plane.
  5686. */
  5687. Matrix.Reflection = function (plane) {
  5688. var matrix = new Matrix();
  5689. Matrix.ReflectionToRef(plane, matrix);
  5690. return matrix;
  5691. };
  5692. /**
  5693. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5694. */
  5695. Matrix.ReflectionToRef = function (plane, result) {
  5696. plane.normalize();
  5697. var x = plane.normal.x;
  5698. var y = plane.normal.y;
  5699. var z = plane.normal.z;
  5700. var temp = -2 * x;
  5701. var temp2 = -2 * y;
  5702. var temp3 = -2 * z;
  5703. result.m[0] = (temp * x) + 1;
  5704. result.m[1] = temp2 * x;
  5705. result.m[2] = temp3 * x;
  5706. result.m[3] = 0.0;
  5707. result.m[4] = temp * y;
  5708. result.m[5] = (temp2 * y) + 1;
  5709. result.m[6] = temp3 * y;
  5710. result.m[7] = 0.0;
  5711. result.m[8] = temp * z;
  5712. result.m[9] = temp2 * z;
  5713. result.m[10] = (temp3 * z) + 1;
  5714. result.m[11] = 0.0;
  5715. result.m[12] = temp * plane.d;
  5716. result.m[13] = temp2 * plane.d;
  5717. result.m[14] = temp3 * plane.d;
  5718. result.m[15] = 1.0;
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5723. */
  5724. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5725. result.m[0] = xaxis.x;
  5726. result.m[1] = xaxis.y;
  5727. result.m[2] = xaxis.z;
  5728. result.m[3] = 0.0;
  5729. result.m[4] = yaxis.x;
  5730. result.m[5] = yaxis.y;
  5731. result.m[6] = yaxis.z;
  5732. result.m[7] = 0.0;
  5733. result.m[8] = zaxis.x;
  5734. result.m[9] = zaxis.y;
  5735. result.m[10] = zaxis.z;
  5736. result.m[11] = 0.0;
  5737. result.m[12] = 0.0;
  5738. result.m[13] = 0.0;
  5739. result.m[14] = 0.0;
  5740. result.m[15] = 1.0;
  5741. result._markAsUpdated();
  5742. };
  5743. /**
  5744. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5745. */
  5746. Matrix.FromQuaternionToRef = function (quat, result) {
  5747. var xx = quat.x * quat.x;
  5748. var yy = quat.y * quat.y;
  5749. var zz = quat.z * quat.z;
  5750. var xy = quat.x * quat.y;
  5751. var zw = quat.z * quat.w;
  5752. var zx = quat.z * quat.x;
  5753. var yw = quat.y * quat.w;
  5754. var yz = quat.y * quat.z;
  5755. var xw = quat.x * quat.w;
  5756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5757. result.m[1] = 2.0 * (xy + zw);
  5758. result.m[2] = 2.0 * (zx - yw);
  5759. result.m[3] = 0.0;
  5760. result.m[4] = 2.0 * (xy - zw);
  5761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5762. result.m[6] = 2.0 * (yz + xw);
  5763. result.m[7] = 0.0;
  5764. result.m[8] = 2.0 * (zx + yw);
  5765. result.m[9] = 2.0 * (yz - xw);
  5766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5767. result.m[11] = 0.0;
  5768. result.m[12] = 0.0;
  5769. result.m[13] = 0.0;
  5770. result.m[14] = 0.0;
  5771. result.m[15] = 1.0;
  5772. result._markAsUpdated();
  5773. };
  5774. Matrix._tempQuaternion = new Quaternion();
  5775. Matrix._xAxis = Vector3.Zero();
  5776. Matrix._yAxis = Vector3.Zero();
  5777. Matrix._zAxis = Vector3.Zero();
  5778. Matrix._updateFlagSeed = 0;
  5779. Matrix._identityReadOnly = Matrix.Identity();
  5780. return Matrix;
  5781. }());
  5782. BABYLON.Matrix = Matrix;
  5783. var Plane = /** @class */ (function () {
  5784. /**
  5785. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5786. */
  5787. function Plane(a, b, c, d) {
  5788. this.normal = new Vector3(a, b, c);
  5789. this.d = d;
  5790. }
  5791. /**
  5792. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5793. */
  5794. Plane.prototype.asArray = function () {
  5795. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5796. };
  5797. // Methods
  5798. /**
  5799. * Returns a new plane copied from the current Plane.
  5800. */
  5801. Plane.prototype.clone = function () {
  5802. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5803. };
  5804. /**
  5805. * Returns the string "Plane".
  5806. */
  5807. Plane.prototype.getClassName = function () {
  5808. return "Plane";
  5809. };
  5810. /**
  5811. * Returns the Plane hash code.
  5812. */
  5813. Plane.prototype.getHashCode = function () {
  5814. var hash = this.normal.getHashCode();
  5815. hash = (hash * 397) ^ (this.d || 0);
  5816. return hash;
  5817. };
  5818. /**
  5819. * Normalize the current Plane in place.
  5820. * Returns the updated Plane.
  5821. */
  5822. Plane.prototype.normalize = function () {
  5823. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5824. var magnitude = 0.0;
  5825. if (norm !== 0) {
  5826. magnitude = 1.0 / norm;
  5827. }
  5828. this.normal.x *= magnitude;
  5829. this.normal.y *= magnitude;
  5830. this.normal.z *= magnitude;
  5831. this.d *= magnitude;
  5832. return this;
  5833. };
  5834. /**
  5835. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5836. */
  5837. Plane.prototype.transform = function (transformation) {
  5838. var transposedMatrix = Matrix.Transpose(transformation);
  5839. var x = this.normal.x;
  5840. var y = this.normal.y;
  5841. var z = this.normal.z;
  5842. var d = this.d;
  5843. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5844. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5845. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5846. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5847. return new Plane(normalX, normalY, normalZ, finalD);
  5848. };
  5849. /**
  5850. * Returns the dot product (float) of the point coordinates and the plane normal.
  5851. */
  5852. Plane.prototype.dotCoordinate = function (point) {
  5853. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5854. };
  5855. /**
  5856. * Updates the current Plane from the plane defined by the three passed points.
  5857. * Returns the updated Plane.
  5858. */
  5859. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5860. var x1 = point2.x - point1.x;
  5861. var y1 = point2.y - point1.y;
  5862. var z1 = point2.z - point1.z;
  5863. var x2 = point3.x - point1.x;
  5864. var y2 = point3.y - point1.y;
  5865. var z2 = point3.z - point1.z;
  5866. var yz = (y1 * z2) - (z1 * y2);
  5867. var xz = (z1 * x2) - (x1 * z2);
  5868. var xy = (x1 * y2) - (y1 * x2);
  5869. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5870. var invPyth;
  5871. if (pyth !== 0) {
  5872. invPyth = 1.0 / pyth;
  5873. }
  5874. else {
  5875. invPyth = 0.0;
  5876. }
  5877. this.normal.x = yz * invPyth;
  5878. this.normal.y = xz * invPyth;
  5879. this.normal.z = xy * invPyth;
  5880. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5881. return this;
  5882. };
  5883. /**
  5884. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5885. */
  5886. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5887. var dot = Vector3.Dot(this.normal, direction);
  5888. return (dot <= epsilon);
  5889. };
  5890. /**
  5891. * Returns the signed distance (float) from the passed point to the Plane.
  5892. */
  5893. Plane.prototype.signedDistanceTo = function (point) {
  5894. return Vector3.Dot(point, this.normal) + this.d;
  5895. };
  5896. // Statics
  5897. /**
  5898. * Returns a new Plane from the passed array.
  5899. */
  5900. Plane.FromArray = function (array) {
  5901. return new Plane(array[0], array[1], array[2], array[3]);
  5902. };
  5903. /**
  5904. * Returns a new Plane defined by the three passed points.
  5905. */
  5906. Plane.FromPoints = function (point1, point2, point3) {
  5907. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5908. result.copyFromPoints(point1, point2, point3);
  5909. return result;
  5910. };
  5911. /**
  5912. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5913. * Note : the vector "normal" is updated because normalized.
  5914. */
  5915. Plane.FromPositionAndNormal = function (origin, normal) {
  5916. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5917. normal.normalize();
  5918. result.normal = normal;
  5919. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5920. return result;
  5921. };
  5922. /**
  5923. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5924. */
  5925. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5926. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5927. return Vector3.Dot(point, normal) + d;
  5928. };
  5929. return Plane;
  5930. }());
  5931. BABYLON.Plane = Plane;
  5932. var Viewport = /** @class */ (function () {
  5933. /**
  5934. * Creates a Viewport object located at (x, y) and sized (width, height).
  5935. */
  5936. function Viewport(x, y, width, height) {
  5937. this.x = x;
  5938. this.y = y;
  5939. this.width = width;
  5940. this.height = height;
  5941. }
  5942. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5943. if (renderWidthOrEngine.getRenderWidth) {
  5944. var engine = renderWidthOrEngine;
  5945. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5946. }
  5947. var renderWidth = renderWidthOrEngine;
  5948. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5949. };
  5950. /**
  5951. * Returns a new Viewport copied from the current one.
  5952. */
  5953. Viewport.prototype.clone = function () {
  5954. return new Viewport(this.x, this.y, this.width, this.height);
  5955. };
  5956. return Viewport;
  5957. }());
  5958. BABYLON.Viewport = Viewport;
  5959. var Frustum = /** @class */ (function () {
  5960. function Frustum() {
  5961. }
  5962. /**
  5963. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5964. */
  5965. Frustum.GetPlanes = function (transform) {
  5966. var frustumPlanes = [];
  5967. for (var index = 0; index < 6; index++) {
  5968. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5969. }
  5970. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5971. return frustumPlanes;
  5972. };
  5973. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5974. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5975. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5976. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5977. frustumPlane.d = transform.m[15] + transform.m[14];
  5978. frustumPlane.normalize();
  5979. };
  5980. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5981. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5982. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5983. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5984. frustumPlane.d = transform.m[15] - transform.m[14];
  5985. frustumPlane.normalize();
  5986. };
  5987. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5988. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5989. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5990. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5991. frustumPlane.d = transform.m[15] + transform.m[12];
  5992. frustumPlane.normalize();
  5993. };
  5994. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5995. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5996. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5997. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5998. frustumPlane.d = transform.m[15] - transform.m[12];
  5999. frustumPlane.normalize();
  6000. };
  6001. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6002. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6003. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6004. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6005. frustumPlane.d = transform.m[15] - transform.m[13];
  6006. frustumPlane.normalize();
  6007. };
  6008. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6009. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6010. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6011. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6012. frustumPlane.d = transform.m[15] + transform.m[13];
  6013. frustumPlane.normalize();
  6014. };
  6015. /**
  6016. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6017. */
  6018. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6019. // Near
  6020. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6021. // Far
  6022. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6023. // Left
  6024. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6025. // Right
  6026. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6027. // Top
  6028. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6029. // Bottom
  6030. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6031. };
  6032. return Frustum;
  6033. }());
  6034. BABYLON.Frustum = Frustum;
  6035. var Space;
  6036. (function (Space) {
  6037. Space[Space["LOCAL"] = 0] = "LOCAL";
  6038. Space[Space["WORLD"] = 1] = "WORLD";
  6039. Space[Space["BONE"] = 2] = "BONE";
  6040. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6041. var Axis = /** @class */ (function () {
  6042. function Axis() {
  6043. }
  6044. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6045. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6046. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6047. return Axis;
  6048. }());
  6049. BABYLON.Axis = Axis;
  6050. ;
  6051. var BezierCurve = /** @class */ (function () {
  6052. function BezierCurve() {
  6053. }
  6054. /**
  6055. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6056. */
  6057. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6058. // Extract X (which is equal to time here)
  6059. var f0 = 1 - 3 * x2 + 3 * x1;
  6060. var f1 = 3 * x2 - 6 * x1;
  6061. var f2 = 3 * x1;
  6062. var refinedT = t;
  6063. for (var i = 0; i < 5; i++) {
  6064. var refinedT2 = refinedT * refinedT;
  6065. var refinedT3 = refinedT2 * refinedT;
  6066. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6067. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6068. refinedT -= (x - t) * slope;
  6069. refinedT = Math.min(1, Math.max(0, refinedT));
  6070. }
  6071. // Resolve cubic bezier for the given x
  6072. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6073. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6074. Math.pow(refinedT, 3);
  6075. };
  6076. return BezierCurve;
  6077. }());
  6078. BABYLON.BezierCurve = BezierCurve;
  6079. var Orientation;
  6080. (function (Orientation) {
  6081. Orientation[Orientation["CW"] = 0] = "CW";
  6082. Orientation[Orientation["CCW"] = 1] = "CCW";
  6083. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6084. var Angle = /** @class */ (function () {
  6085. /**
  6086. * Creates an Angle object of "radians" radians (float).
  6087. */
  6088. function Angle(radians) {
  6089. var _this = this;
  6090. /**
  6091. * Returns the Angle value in degrees (float).
  6092. */
  6093. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6094. /**
  6095. * Returns the Angle value in radians (float).
  6096. */
  6097. this.radians = function () { return _this._radians; };
  6098. this._radians = radians;
  6099. if (this._radians < 0.0)
  6100. this._radians += (2.0 * Math.PI);
  6101. }
  6102. /**
  6103. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6104. */
  6105. Angle.BetweenTwoPoints = function (a, b) {
  6106. var delta = b.subtract(a);
  6107. var theta = Math.atan2(delta.y, delta.x);
  6108. return new Angle(theta);
  6109. };
  6110. /**
  6111. * Returns a new Angle object from the passed float in radians.
  6112. */
  6113. Angle.FromRadians = function (radians) {
  6114. return new Angle(radians);
  6115. };
  6116. /**
  6117. * Returns a new Angle object from the passed float in degrees.
  6118. */
  6119. Angle.FromDegrees = function (degrees) {
  6120. return new Angle(degrees * Math.PI / 180.0);
  6121. };
  6122. return Angle;
  6123. }());
  6124. BABYLON.Angle = Angle;
  6125. var Arc2 = /** @class */ (function () {
  6126. /**
  6127. * Creates an Arc object from the three passed points : start, middle and end.
  6128. */
  6129. function Arc2(startPoint, midPoint, endPoint) {
  6130. this.startPoint = startPoint;
  6131. this.midPoint = midPoint;
  6132. this.endPoint = endPoint;
  6133. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6134. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6135. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6136. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6137. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6138. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6139. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6140. var a1 = this.startAngle.degrees();
  6141. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6142. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6143. // angles correction
  6144. if (a2 - a1 > +180.0)
  6145. a2 -= 360.0;
  6146. if (a2 - a1 < -180.0)
  6147. a2 += 360.0;
  6148. if (a3 - a2 > +180.0)
  6149. a3 -= 360.0;
  6150. if (a3 - a2 < -180.0)
  6151. a3 += 360.0;
  6152. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6153. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6154. }
  6155. return Arc2;
  6156. }());
  6157. BABYLON.Arc2 = Arc2;
  6158. var Path2 = /** @class */ (function () {
  6159. /**
  6160. * Creates a Path2 object from the starting 2D coordinates x and y.
  6161. */
  6162. function Path2(x, y) {
  6163. this._points = new Array();
  6164. this._length = 0.0;
  6165. this.closed = false;
  6166. this._points.push(new Vector2(x, y));
  6167. }
  6168. /**
  6169. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6170. * Returns the updated Path2.
  6171. */
  6172. Path2.prototype.addLineTo = function (x, y) {
  6173. if (this.closed) {
  6174. return this;
  6175. }
  6176. var newPoint = new Vector2(x, y);
  6177. var previousPoint = this._points[this._points.length - 1];
  6178. this._points.push(newPoint);
  6179. this._length += newPoint.subtract(previousPoint).length();
  6180. return this;
  6181. };
  6182. /**
  6183. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6184. * Returns the updated Path2.
  6185. */
  6186. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6187. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6188. if (this.closed) {
  6189. return this;
  6190. }
  6191. var startPoint = this._points[this._points.length - 1];
  6192. var midPoint = new Vector2(midX, midY);
  6193. var endPoint = new Vector2(endX, endY);
  6194. var arc = new Arc2(startPoint, midPoint, endPoint);
  6195. var increment = arc.angle.radians() / numberOfSegments;
  6196. if (arc.orientation === Orientation.CW)
  6197. increment *= -1;
  6198. var currentAngle = arc.startAngle.radians() + increment;
  6199. for (var i = 0; i < numberOfSegments; i++) {
  6200. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6201. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6202. this.addLineTo(x, y);
  6203. currentAngle += increment;
  6204. }
  6205. return this;
  6206. };
  6207. /**
  6208. * Closes the Path2.
  6209. * Returns the Path2.
  6210. */
  6211. Path2.prototype.close = function () {
  6212. this.closed = true;
  6213. return this;
  6214. };
  6215. /**
  6216. * Returns the Path2 total length (float).
  6217. */
  6218. Path2.prototype.length = function () {
  6219. var result = this._length;
  6220. if (!this.closed) {
  6221. var lastPoint = this._points[this._points.length - 1];
  6222. var firstPoint = this._points[0];
  6223. result += (firstPoint.subtract(lastPoint).length());
  6224. }
  6225. return result;
  6226. };
  6227. /**
  6228. * Returns the Path2 internal array of points.
  6229. */
  6230. Path2.prototype.getPoints = function () {
  6231. return this._points;
  6232. };
  6233. /**
  6234. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6235. */
  6236. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6237. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6238. return Vector2.Zero();
  6239. }
  6240. var lengthPosition = normalizedLengthPosition * this.length();
  6241. var previousOffset = 0;
  6242. for (var i = 0; i < this._points.length; i++) {
  6243. var j = (i + 1) % this._points.length;
  6244. var a = this._points[i];
  6245. var b = this._points[j];
  6246. var bToA = b.subtract(a);
  6247. var nextOffset = (bToA.length() + previousOffset);
  6248. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6249. var dir = bToA.normalize();
  6250. var localOffset = lengthPosition - previousOffset;
  6251. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6252. }
  6253. previousOffset = nextOffset;
  6254. }
  6255. return Vector2.Zero();
  6256. };
  6257. /**
  6258. * Returns a new Path2 starting at the coordinates (x, y).
  6259. */
  6260. Path2.StartingAt = function (x, y) {
  6261. return new Path2(x, y);
  6262. };
  6263. return Path2;
  6264. }());
  6265. BABYLON.Path2 = Path2;
  6266. var Path3D = /** @class */ (function () {
  6267. /**
  6268. * new Path3D(path, normal, raw)
  6269. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6270. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6271. * path : an array of Vector3, the curve axis of the Path3D
  6272. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6273. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6274. */
  6275. function Path3D(path, firstNormal, raw) {
  6276. if (firstNormal === void 0) { firstNormal = null; }
  6277. this.path = path;
  6278. this._curve = new Array();
  6279. this._distances = new Array();
  6280. this._tangents = new Array();
  6281. this._normals = new Array();
  6282. this._binormals = new Array();
  6283. for (var p = 0; p < path.length; p++) {
  6284. this._curve[p] = path[p].clone(); // hard copy
  6285. }
  6286. this._raw = raw || false;
  6287. this._compute(firstNormal);
  6288. }
  6289. /**
  6290. * Returns the Path3D array of successive Vector3 designing its curve.
  6291. */
  6292. Path3D.prototype.getCurve = function () {
  6293. return this._curve;
  6294. };
  6295. /**
  6296. * Returns an array populated with tangent vectors on each Path3D curve point.
  6297. */
  6298. Path3D.prototype.getTangents = function () {
  6299. return this._tangents;
  6300. };
  6301. /**
  6302. * Returns an array populated with normal vectors on each Path3D curve point.
  6303. */
  6304. Path3D.prototype.getNormals = function () {
  6305. return this._normals;
  6306. };
  6307. /**
  6308. * Returns an array populated with binormal vectors on each Path3D curve point.
  6309. */
  6310. Path3D.prototype.getBinormals = function () {
  6311. return this._binormals;
  6312. };
  6313. /**
  6314. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6315. */
  6316. Path3D.prototype.getDistances = function () {
  6317. return this._distances;
  6318. };
  6319. /**
  6320. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6321. * Returns the same object updated.
  6322. */
  6323. Path3D.prototype.update = function (path, firstNormal) {
  6324. if (firstNormal === void 0) { firstNormal = null; }
  6325. for (var p = 0; p < path.length; p++) {
  6326. this._curve[p].x = path[p].x;
  6327. this._curve[p].y = path[p].y;
  6328. this._curve[p].z = path[p].z;
  6329. }
  6330. this._compute(firstNormal);
  6331. return this;
  6332. };
  6333. // private function compute() : computes tangents, normals and binormals
  6334. Path3D.prototype._compute = function (firstNormal) {
  6335. var l = this._curve.length;
  6336. // first and last tangents
  6337. this._tangents[0] = this._getFirstNonNullVector(0);
  6338. if (!this._raw) {
  6339. this._tangents[0].normalize();
  6340. }
  6341. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6342. if (!this._raw) {
  6343. this._tangents[l - 1].normalize();
  6344. }
  6345. // normals and binormals at first point : arbitrary vector with _normalVector()
  6346. var tg0 = this._tangents[0];
  6347. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6348. this._normals[0] = pp0;
  6349. if (!this._raw) {
  6350. this._normals[0].normalize();
  6351. }
  6352. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6353. if (!this._raw) {
  6354. this._binormals[0].normalize();
  6355. }
  6356. this._distances[0] = 0.0;
  6357. // normals and binormals : next points
  6358. var prev; // previous vector (segment)
  6359. var cur; // current vector (segment)
  6360. var curTang; // current tangent
  6361. // previous normal
  6362. var prevBinor; // previous binormal
  6363. for (var i = 1; i < l; i++) {
  6364. // tangents
  6365. prev = this._getLastNonNullVector(i);
  6366. if (i < l - 1) {
  6367. cur = this._getFirstNonNullVector(i);
  6368. this._tangents[i] = prev.add(cur);
  6369. this._tangents[i].normalize();
  6370. }
  6371. this._distances[i] = this._distances[i - 1] + prev.length();
  6372. // normals and binormals
  6373. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6374. curTang = this._tangents[i];
  6375. prevBinor = this._binormals[i - 1];
  6376. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6377. if (!this._raw) {
  6378. this._normals[i].normalize();
  6379. }
  6380. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6381. if (!this._raw) {
  6382. this._binormals[i].normalize();
  6383. }
  6384. }
  6385. };
  6386. // private function getFirstNonNullVector(index)
  6387. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6388. Path3D.prototype._getFirstNonNullVector = function (index) {
  6389. var i = 1;
  6390. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6391. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6392. i++;
  6393. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6394. }
  6395. return nNVector;
  6396. };
  6397. // private function getLastNonNullVector(index)
  6398. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6399. Path3D.prototype._getLastNonNullVector = function (index) {
  6400. var i = 1;
  6401. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6402. while (nLVector.length() === 0 && index > i + 1) {
  6403. i++;
  6404. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6405. }
  6406. return nLVector;
  6407. };
  6408. // private function normalVector(v0, vt, va) :
  6409. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6410. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6411. Path3D.prototype._normalVector = function (v0, vt, va) {
  6412. var normal0;
  6413. var tgl = vt.length();
  6414. if (tgl === 0.0) {
  6415. tgl = 1.0;
  6416. }
  6417. if (va === undefined || va === null) {
  6418. var point;
  6419. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6420. point = new Vector3(0.0, -1.0, 0.0);
  6421. }
  6422. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6423. point = new Vector3(1.0, 0.0, 0.0);
  6424. }
  6425. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6426. point = new Vector3(0.0, 0.0, 1.0);
  6427. }
  6428. else {
  6429. point = Vector3.Zero();
  6430. }
  6431. normal0 = Vector3.Cross(vt, point);
  6432. }
  6433. else {
  6434. normal0 = Vector3.Cross(vt, va);
  6435. Vector3.CrossToRef(normal0, vt, normal0);
  6436. }
  6437. normal0.normalize();
  6438. return normal0;
  6439. };
  6440. return Path3D;
  6441. }());
  6442. BABYLON.Path3D = Path3D;
  6443. var Curve3 = /** @class */ (function () {
  6444. /**
  6445. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6446. * A Curve3 is designed from a series of successive Vector3.
  6447. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6448. */
  6449. function Curve3(points) {
  6450. this._length = 0.0;
  6451. this._points = points;
  6452. this._length = this._computeLength(points);
  6453. }
  6454. /**
  6455. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6456. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6457. * @param v1 (Vector3) the control point
  6458. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6459. * @param nbPoints (integer) the wanted number of points in the curve
  6460. */
  6461. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6462. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6463. var bez = new Array();
  6464. var equation = function (t, val0, val1, val2) {
  6465. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6466. return res;
  6467. };
  6468. for (var i = 0; i <= nbPoints; i++) {
  6469. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6470. }
  6471. return new Curve3(bez);
  6472. };
  6473. /**
  6474. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6475. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6476. * @param v1 (Vector3) the first control point
  6477. * @param v2 (Vector3) the second control point
  6478. * @param v3 (Vector3) the end point of the Cubic Bezier
  6479. * @param nbPoints (integer) the wanted number of points in the curve
  6480. */
  6481. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6482. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6483. var bez = new Array();
  6484. var equation = function (t, val0, val1, val2, val3) {
  6485. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6486. return res;
  6487. };
  6488. for (var i = 0; i <= nbPoints; i++) {
  6489. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6490. }
  6491. return new Curve3(bez);
  6492. };
  6493. /**
  6494. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6495. * @param p1 (Vector3) the origin point of the Hermite Spline
  6496. * @param t1 (Vector3) the tangent vector at the origin point
  6497. * @param p2 (Vector3) the end point of the Hermite Spline
  6498. * @param t2 (Vector3) the tangent vector at the end point
  6499. * @param nbPoints (integer) the wanted number of points in the curve
  6500. */
  6501. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6502. var hermite = new Array();
  6503. var step = 1.0 / nbPoints;
  6504. for (var i = 0; i <= nbPoints; i++) {
  6505. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6506. }
  6507. return new Curve3(hermite);
  6508. };
  6509. /**
  6510. * Returns a Curve3 object along a CatmullRom Spline curve :
  6511. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6512. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6513. */
  6514. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6515. var totalPoints = new Array();
  6516. totalPoints.push(points[0].clone());
  6517. Array.prototype.push.apply(totalPoints, points);
  6518. totalPoints.push(points[points.length - 1].clone());
  6519. var catmullRom = new Array();
  6520. var step = 1.0 / nbPoints;
  6521. var amount = 0.0;
  6522. for (var i = 0; i < totalPoints.length - 3; i++) {
  6523. amount = 0;
  6524. for (var c = 0; c < nbPoints; c++) {
  6525. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6526. amount += step;
  6527. }
  6528. }
  6529. i--;
  6530. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6531. return new Curve3(catmullRom);
  6532. };
  6533. /**
  6534. * Returns the Curve3 stored array of successive Vector3
  6535. */
  6536. Curve3.prototype.getPoints = function () {
  6537. return this._points;
  6538. };
  6539. /**
  6540. * Returns the computed length (float) of the curve.
  6541. */
  6542. Curve3.prototype.length = function () {
  6543. return this._length;
  6544. };
  6545. /**
  6546. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6547. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6548. * curveA and curveB keep unchanged.
  6549. */
  6550. Curve3.prototype.continue = function (curve) {
  6551. var lastPoint = this._points[this._points.length - 1];
  6552. var continuedPoints = this._points.slice();
  6553. var curvePoints = curve.getPoints();
  6554. for (var i = 1; i < curvePoints.length; i++) {
  6555. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6556. }
  6557. var continuedCurve = new Curve3(continuedPoints);
  6558. return continuedCurve;
  6559. };
  6560. Curve3.prototype._computeLength = function (path) {
  6561. var l = 0;
  6562. for (var i = 1; i < path.length; i++) {
  6563. l += (path[i].subtract(path[i - 1])).length();
  6564. }
  6565. return l;
  6566. };
  6567. return Curve3;
  6568. }());
  6569. BABYLON.Curve3 = Curve3;
  6570. // Vertex formats
  6571. var PositionNormalVertex = /** @class */ (function () {
  6572. function PositionNormalVertex(position, normal) {
  6573. if (position === void 0) { position = Vector3.Zero(); }
  6574. if (normal === void 0) { normal = Vector3.Up(); }
  6575. this.position = position;
  6576. this.normal = normal;
  6577. }
  6578. PositionNormalVertex.prototype.clone = function () {
  6579. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6580. };
  6581. return PositionNormalVertex;
  6582. }());
  6583. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6584. var PositionNormalTextureVertex = /** @class */ (function () {
  6585. function PositionNormalTextureVertex(position, normal, uv) {
  6586. if (position === void 0) { position = Vector3.Zero(); }
  6587. if (normal === void 0) { normal = Vector3.Up(); }
  6588. if (uv === void 0) { uv = Vector2.Zero(); }
  6589. this.position = position;
  6590. this.normal = normal;
  6591. this.uv = uv;
  6592. }
  6593. PositionNormalTextureVertex.prototype.clone = function () {
  6594. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6595. };
  6596. return PositionNormalTextureVertex;
  6597. }());
  6598. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6599. // Temporary pre-allocated objects for engine internal use
  6600. // usage in any internal function :
  6601. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6602. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6603. var Tmp = /** @class */ (function () {
  6604. function Tmp() {
  6605. }
  6606. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6607. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6608. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6609. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6610. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6611. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6612. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6613. Matrix.Zero(), Matrix.Zero(),
  6614. Matrix.Zero(), Matrix.Zero(),
  6615. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6616. return Tmp;
  6617. }());
  6618. BABYLON.Tmp = Tmp;
  6619. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6620. var MathTmp = /** @class */ (function () {
  6621. function MathTmp() {
  6622. }
  6623. MathTmp.Vector3 = [Vector3.Zero()];
  6624. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6625. MathTmp.Quaternion = [Quaternion.Zero()];
  6626. return MathTmp;
  6627. }());
  6628. })(BABYLON || (BABYLON = {}));
  6629. //# sourceMappingURL=babylon.math.js.map
  6630. var BABYLON;
  6631. (function (BABYLON) {
  6632. var Scalar = /** @class */ (function () {
  6633. function Scalar() {
  6634. }
  6635. /**
  6636. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6637. */
  6638. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6639. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6640. var num = a - b;
  6641. return -epsilon <= num && num <= epsilon;
  6642. };
  6643. /**
  6644. * Returns a string : the upper case translation of the number i to hexadecimal.
  6645. */
  6646. Scalar.ToHex = function (i) {
  6647. var str = i.toString(16);
  6648. if (i <= 15) {
  6649. return ("0" + str).toUpperCase();
  6650. }
  6651. return str.toUpperCase();
  6652. };
  6653. /**
  6654. * Returns -1 if value is negative and +1 is value is positive.
  6655. * Returns the value itself if it's equal to zero.
  6656. */
  6657. Scalar.Sign = function (value) {
  6658. value = +value; // convert to a number
  6659. if (value === 0 || isNaN(value))
  6660. return value;
  6661. return value > 0 ? 1 : -1;
  6662. };
  6663. /**
  6664. * Returns the value itself if it's between min and max.
  6665. * Returns min if the value is lower than min.
  6666. * Returns max if the value is greater than max.
  6667. */
  6668. Scalar.Clamp = function (value, min, max) {
  6669. if (min === void 0) { min = 0; }
  6670. if (max === void 0) { max = 1; }
  6671. return Math.min(max, Math.max(min, value));
  6672. };
  6673. /**
  6674. * Returns the log2 of value.
  6675. */
  6676. Scalar.Log2 = function (value) {
  6677. return Math.log(value) * Math.LOG2E;
  6678. };
  6679. /**
  6680. * Loops the value, so that it is never larger than length and never smaller than 0.
  6681. *
  6682. * This is similar to the modulo operator but it works with floating point numbers.
  6683. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6684. * With t = 5 and length = 2.5, the result would be 0.0.
  6685. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6686. */
  6687. Scalar.Repeat = function (value, length) {
  6688. return value - Math.floor(value / length) * length;
  6689. };
  6690. /**
  6691. * Normalize the value between 0.0 and 1.0 using min and max values
  6692. */
  6693. Scalar.Normalize = function (value, min, max) {
  6694. return (value - min) / (max - min);
  6695. };
  6696. /**
  6697. * Denormalize the value from 0.0 and 1.0 using min and max values
  6698. */
  6699. Scalar.Denormalize = function (normalized, min, max) {
  6700. return (normalized * (max - min) + min);
  6701. };
  6702. /**
  6703. * Calculates the shortest difference between two given angles given in degrees.
  6704. */
  6705. Scalar.DeltaAngle = function (current, target) {
  6706. var num = Scalar.Repeat(target - current, 360.0);
  6707. if (num > 180.0) {
  6708. num -= 360.0;
  6709. }
  6710. return num;
  6711. };
  6712. /**
  6713. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6714. *
  6715. * The returned value will move back and forth between 0 and length
  6716. */
  6717. Scalar.PingPong = function (tx, length) {
  6718. var t = Scalar.Repeat(tx, length * 2.0);
  6719. return length - Math.abs(t - length);
  6720. };
  6721. /**
  6722. * Interpolates between min and max with smoothing at the limits.
  6723. *
  6724. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6725. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6726. */
  6727. Scalar.SmoothStep = function (from, to, tx) {
  6728. var t = Scalar.Clamp(tx);
  6729. t = -2.0 * t * t * t + 3.0 * t * t;
  6730. return to * t + from * (1.0 - t);
  6731. };
  6732. /**
  6733. * Moves a value current towards target.
  6734. *
  6735. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6736. * Negative values of maxDelta pushes the value away from target.
  6737. */
  6738. Scalar.MoveTowards = function (current, target, maxDelta) {
  6739. var result = 0;
  6740. if (Math.abs(target - current) <= maxDelta) {
  6741. result = target;
  6742. }
  6743. else {
  6744. result = current + Scalar.Sign(target - current) * maxDelta;
  6745. }
  6746. return result;
  6747. };
  6748. /**
  6749. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6750. *
  6751. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6752. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6753. */
  6754. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6755. var num = Scalar.DeltaAngle(current, target);
  6756. var result = 0;
  6757. if (-maxDelta < num && num < maxDelta) {
  6758. result = target;
  6759. }
  6760. else {
  6761. target = current + num;
  6762. result = Scalar.MoveTowards(current, target, maxDelta);
  6763. }
  6764. return result;
  6765. };
  6766. /**
  6767. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6768. */
  6769. Scalar.Lerp = function (start, end, amount) {
  6770. return start + ((end - start) * amount);
  6771. };
  6772. /**
  6773. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6774. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6775. */
  6776. Scalar.LerpAngle = function (start, end, amount) {
  6777. var num = Scalar.Repeat(end - start, 360.0);
  6778. if (num > 180.0) {
  6779. num -= 360.0;
  6780. }
  6781. return start + num * Scalar.Clamp(amount);
  6782. };
  6783. /**
  6784. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6785. */
  6786. Scalar.InverseLerp = function (a, b, value) {
  6787. var result = 0;
  6788. if (a != b) {
  6789. result = Scalar.Clamp((value - a) / (b - a));
  6790. }
  6791. else {
  6792. result = 0.0;
  6793. }
  6794. return result;
  6795. };
  6796. /**
  6797. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6798. */
  6799. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6800. var squared = amount * amount;
  6801. var cubed = amount * squared;
  6802. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6803. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6804. var part3 = (cubed - (2.0 * squared)) + amount;
  6805. var part4 = cubed - squared;
  6806. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6807. };
  6808. /**
  6809. * Returns a random float number between and min and max values
  6810. */
  6811. Scalar.RandomRange = function (min, max) {
  6812. if (min === max)
  6813. return min;
  6814. return ((Math.random() * (max - min)) + min);
  6815. };
  6816. /**
  6817. * This function returns percentage of a number in a given range.
  6818. *
  6819. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6820. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6821. */
  6822. Scalar.RangeToPercent = function (number, min, max) {
  6823. return ((number - min) / (max - min));
  6824. };
  6825. /**
  6826. * This function returns number that corresponds to the percentage in a given range.
  6827. *
  6828. * PercentToRange(0.34,0,100) will return 34.
  6829. */
  6830. Scalar.PercentToRange = function (percent, min, max) {
  6831. return ((max - min) * percent + min);
  6832. };
  6833. /**
  6834. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6835. * @param angle The angle to normalize in radian.
  6836. * @return The converted angle.
  6837. */
  6838. Scalar.NormalizeRadians = function (angle) {
  6839. // More precise but slower version kept for reference.
  6840. // angle = angle % Tools.TwoPi;
  6841. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6842. //if (angle > Math.PI) {
  6843. // angle -= Tools.TwoPi;
  6844. //}
  6845. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6846. return angle;
  6847. };
  6848. /**
  6849. * Two pi constants convenient for computation.
  6850. */
  6851. Scalar.TwoPi = Math.PI * 2;
  6852. return Scalar;
  6853. }());
  6854. BABYLON.Scalar = Scalar;
  6855. })(BABYLON || (BABYLON = {}));
  6856. //# sourceMappingURL=babylon.math.scalar.js.map
  6857. //# sourceMappingURL=babylon.mixins.js.map
  6858. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6859. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6860. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6861. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6862. //# sourceMappingURL=babylon.webgl2.js.map
  6863. var BABYLON;
  6864. (function (BABYLON) {
  6865. var __decoratorInitialStore = {};
  6866. var __mergedStore = {};
  6867. var _copySource = function (creationFunction, source, instanciate) {
  6868. var destination = creationFunction();
  6869. // Tags
  6870. if (BABYLON.Tags) {
  6871. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6872. }
  6873. var classStore = getMergedStore(destination);
  6874. // Properties
  6875. for (var property in classStore) {
  6876. var propertyDescriptor = classStore[property];
  6877. var sourceProperty = source[property];
  6878. var propertyType = propertyDescriptor.type;
  6879. if (sourceProperty !== undefined && sourceProperty !== null) {
  6880. switch (propertyType) {
  6881. case 0: // Value
  6882. case 6:// Mesh reference
  6883. destination[property] = sourceProperty;
  6884. break;
  6885. case 1:// Texture
  6886. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6887. break;
  6888. case 2: // Color3
  6889. case 3: // FresnelParameters
  6890. case 4: // Vector2
  6891. case 5: // Vector3
  6892. case 7: // Color Curves
  6893. case 10:// Quaternion
  6894. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6895. break;
  6896. }
  6897. }
  6898. }
  6899. return destination;
  6900. };
  6901. function getDirectStore(target) {
  6902. var classKey = target.getClassName();
  6903. if (!__decoratorInitialStore[classKey]) {
  6904. __decoratorInitialStore[classKey] = {};
  6905. }
  6906. return __decoratorInitialStore[classKey];
  6907. }
  6908. /**
  6909. * Return the list of properties flagged as serializable
  6910. * @param target: host object
  6911. */
  6912. function getMergedStore(target) {
  6913. var classKey = target.getClassName();
  6914. if (__mergedStore[classKey]) {
  6915. return __mergedStore[classKey];
  6916. }
  6917. __mergedStore[classKey] = {};
  6918. var store = __mergedStore[classKey];
  6919. var currentTarget = target;
  6920. var currentKey = classKey;
  6921. while (currentKey) {
  6922. var initialStore = __decoratorInitialStore[currentKey];
  6923. for (var property in initialStore) {
  6924. store[property] = initialStore[property];
  6925. }
  6926. var parent_1 = void 0;
  6927. var done = false;
  6928. do {
  6929. parent_1 = Object.getPrototypeOf(currentTarget);
  6930. if (!parent_1.getClassName) {
  6931. done = true;
  6932. break;
  6933. }
  6934. if (parent_1.getClassName() !== currentKey) {
  6935. break;
  6936. }
  6937. currentTarget = parent_1;
  6938. } while (parent_1);
  6939. if (done) {
  6940. break;
  6941. }
  6942. currentKey = parent_1.getClassName();
  6943. currentTarget = parent_1;
  6944. }
  6945. return store;
  6946. }
  6947. function generateSerializableMember(type, sourceName) {
  6948. return function (target, propertyKey) {
  6949. var classStore = getDirectStore(target);
  6950. if (!classStore[propertyKey]) {
  6951. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6952. }
  6953. };
  6954. }
  6955. function generateExpandMember(setCallback, targetKey) {
  6956. if (targetKey === void 0) { targetKey = null; }
  6957. return function (target, propertyKey) {
  6958. var key = targetKey || ("_" + propertyKey);
  6959. Object.defineProperty(target, propertyKey, {
  6960. get: function () {
  6961. return this[key];
  6962. },
  6963. set: function (value) {
  6964. if (this[key] === value) {
  6965. return;
  6966. }
  6967. this[key] = value;
  6968. target[setCallback].apply(this);
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. };
  6974. }
  6975. function expandToProperty(callback, targetKey) {
  6976. if (targetKey === void 0) { targetKey = null; }
  6977. return generateExpandMember(callback, targetKey);
  6978. }
  6979. BABYLON.expandToProperty = expandToProperty;
  6980. function serialize(sourceName) {
  6981. return generateSerializableMember(0, sourceName); // value member
  6982. }
  6983. BABYLON.serialize = serialize;
  6984. function serializeAsTexture(sourceName) {
  6985. return generateSerializableMember(1, sourceName); // texture member
  6986. }
  6987. BABYLON.serializeAsTexture = serializeAsTexture;
  6988. function serializeAsColor3(sourceName) {
  6989. return generateSerializableMember(2, sourceName); // color3 member
  6990. }
  6991. BABYLON.serializeAsColor3 = serializeAsColor3;
  6992. function serializeAsFresnelParameters(sourceName) {
  6993. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6994. }
  6995. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6996. function serializeAsVector2(sourceName) {
  6997. return generateSerializableMember(4, sourceName); // vector2 member
  6998. }
  6999. BABYLON.serializeAsVector2 = serializeAsVector2;
  7000. function serializeAsVector3(sourceName) {
  7001. return generateSerializableMember(5, sourceName); // vector3 member
  7002. }
  7003. BABYLON.serializeAsVector3 = serializeAsVector3;
  7004. function serializeAsMeshReference(sourceName) {
  7005. return generateSerializableMember(6, sourceName); // mesh reference member
  7006. }
  7007. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7008. function serializeAsColorCurves(sourceName) {
  7009. return generateSerializableMember(7, sourceName); // color curves
  7010. }
  7011. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7012. function serializeAsColor4(sourceName) {
  7013. return generateSerializableMember(8, sourceName); // color 4
  7014. }
  7015. BABYLON.serializeAsColor4 = serializeAsColor4;
  7016. function serializeAsImageProcessingConfiguration(sourceName) {
  7017. return generateSerializableMember(9, sourceName); // image processing
  7018. }
  7019. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7020. function serializeAsQuaternion(sourceName) {
  7021. return generateSerializableMember(10, sourceName); // quaternion member
  7022. }
  7023. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7024. var SerializationHelper = /** @class */ (function () {
  7025. function SerializationHelper() {
  7026. }
  7027. SerializationHelper.Serialize = function (entity, serializationObject) {
  7028. if (!serializationObject) {
  7029. serializationObject = {};
  7030. }
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7034. }
  7035. var serializedProperties = getMergedStore(entity);
  7036. // Properties
  7037. for (var property in serializedProperties) {
  7038. var propertyDescriptor = serializedProperties[property];
  7039. var targetPropertyName = propertyDescriptor.sourceName || property;
  7040. var propertyType = propertyDescriptor.type;
  7041. var sourceProperty = entity[property];
  7042. if (sourceProperty !== undefined && sourceProperty !== null) {
  7043. switch (propertyType) {
  7044. case 0:// Value
  7045. serializationObject[targetPropertyName] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7049. break;
  7050. case 2:// Color3
  7051. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7052. break;
  7053. case 3:// FresnelParameters
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. case 4:// Vector2
  7057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7058. break;
  7059. case 5:// Vector3
  7060. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7061. break;
  7062. case 6:// Mesh reference
  7063. serializationObject[targetPropertyName] = sourceProperty.id;
  7064. break;
  7065. case 7:// Color Curves
  7066. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7067. break;
  7068. case 8:// Color 4
  7069. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7070. break;
  7071. case 9:// Image Processing
  7072. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7073. break;
  7074. }
  7075. }
  7076. }
  7077. return serializationObject;
  7078. };
  7079. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7080. if (rootUrl === void 0) { rootUrl = null; }
  7081. var destination = creationFunction();
  7082. if (!rootUrl) {
  7083. rootUrl = "";
  7084. }
  7085. // Tags
  7086. if (BABYLON.Tags) {
  7087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7088. }
  7089. var classStore = getMergedStore(destination);
  7090. // Properties
  7091. for (var property in classStore) {
  7092. var propertyDescriptor = classStore[property];
  7093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7094. var propertyType = propertyDescriptor.type;
  7095. if (sourceProperty !== undefined && sourceProperty !== null) {
  7096. var dest = destination;
  7097. switch (propertyType) {
  7098. case 0:// Value
  7099. dest[property] = sourceProperty;
  7100. break;
  7101. case 1:// Texture
  7102. if (scene) {
  7103. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7104. }
  7105. break;
  7106. case 2:// Color3
  7107. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7108. break;
  7109. case 3:// FresnelParameters
  7110. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7111. break;
  7112. case 4:// Vector2
  7113. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7114. break;
  7115. case 5:// Vector3
  7116. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7117. break;
  7118. case 6:// Mesh reference
  7119. if (scene) {
  7120. dest[property] = scene.getLastMeshByID(sourceProperty);
  7121. }
  7122. break;
  7123. case 7:// Color Curves
  7124. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7125. break;
  7126. case 8:// Color 4
  7127. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7128. break;
  7129. case 9:// Image Processing
  7130. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7131. break;
  7132. }
  7133. }
  7134. }
  7135. return destination;
  7136. };
  7137. SerializationHelper.Clone = function (creationFunction, source) {
  7138. return _copySource(creationFunction, source, false);
  7139. };
  7140. SerializationHelper.Instanciate = function (creationFunction, source) {
  7141. return _copySource(creationFunction, source, true);
  7142. };
  7143. return SerializationHelper;
  7144. }());
  7145. BABYLON.SerializationHelper = SerializationHelper;
  7146. })(BABYLON || (BABYLON = {}));
  7147. //# sourceMappingURL=babylon.decorators.js.map
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. /**
  7151. * Wrapper class for promise with external resolve and reject.
  7152. */
  7153. var Deferred = /** @class */ (function () {
  7154. /**
  7155. * Constructor for this deferred object.
  7156. */
  7157. function Deferred() {
  7158. var _this = this;
  7159. this.promise = new Promise(function (resolve, reject) {
  7160. _this._resolve = resolve;
  7161. _this._reject = reject;
  7162. });
  7163. }
  7164. Object.defineProperty(Deferred.prototype, "resolve", {
  7165. /**
  7166. * The resolve method of the promise associated with this deferred object.
  7167. */
  7168. get: function () {
  7169. return this._resolve;
  7170. },
  7171. enumerable: true,
  7172. configurable: true
  7173. });
  7174. Object.defineProperty(Deferred.prototype, "reject", {
  7175. /**
  7176. * The reject method of the promise associated with this deferred object.
  7177. */
  7178. get: function () {
  7179. return this._reject;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. return Deferred;
  7185. }());
  7186. BABYLON.Deferred = Deferred;
  7187. })(BABYLON || (BABYLON = {}));
  7188. //# sourceMappingURL=babylon.deferred.js.map
  7189. var BABYLON;
  7190. (function (BABYLON) {
  7191. /**
  7192. * A class serves as a medium between the observable and its observers
  7193. */
  7194. var EventState = /** @class */ (function () {
  7195. /**
  7196. * Create a new EventState
  7197. * @param mask defines the mask associated with this state
  7198. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7199. * @param target defines the original target of the state
  7200. * @param currentTarget defines the current target of the state
  7201. */
  7202. function EventState(mask, skipNextObservers, target, currentTarget) {
  7203. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7204. this.initalize(mask, skipNextObservers, target, currentTarget);
  7205. }
  7206. /**
  7207. * Initialize the current event state
  7208. * @param mask defines the mask associated with this state
  7209. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7210. * @param target defines the original target of the state
  7211. * @param currentTarget defines the current target of the state
  7212. * @returns the current event state
  7213. */
  7214. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7215. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7216. this.mask = mask;
  7217. this.skipNextObservers = skipNextObservers;
  7218. this.target = target;
  7219. this.currentTarget = currentTarget;
  7220. return this;
  7221. };
  7222. return EventState;
  7223. }());
  7224. BABYLON.EventState = EventState;
  7225. /**
  7226. * Represent an Observer registered to a given Observable object.
  7227. */
  7228. var Observer = /** @class */ (function () {
  7229. /**
  7230. * Creates a new observer
  7231. * @param callback defines the callback to call when the observer is notified
  7232. * @param mask defines the mask of the observer (used to filter notifications)
  7233. * @param scope defines the current scope used to restore the JS context
  7234. */
  7235. function Observer(
  7236. /**
  7237. * Defines the callback to call when the observer is notified
  7238. */
  7239. callback,
  7240. /**
  7241. * Defines the mask of the observer (used to filter notifications)
  7242. */
  7243. mask,
  7244. /**
  7245. * Defines the current scope used to restore the JS context
  7246. */
  7247. scope) {
  7248. if (scope === void 0) { scope = null; }
  7249. this.callback = callback;
  7250. this.mask = mask;
  7251. this.scope = scope;
  7252. /** @ignore */
  7253. this._willBeUnregistered = false;
  7254. /**
  7255. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7256. */
  7257. this.unregisterOnNextCall = false;
  7258. }
  7259. return Observer;
  7260. }());
  7261. BABYLON.Observer = Observer;
  7262. /**
  7263. * Represent a list of observers registered to multiple Observables object.
  7264. */
  7265. var MultiObserver = /** @class */ (function () {
  7266. function MultiObserver() {
  7267. }
  7268. /**
  7269. * Release associated resources
  7270. */
  7271. MultiObserver.prototype.dispose = function () {
  7272. if (this._observers && this._observables) {
  7273. for (var index = 0; index < this._observers.length; index++) {
  7274. this._observables[index].remove(this._observers[index]);
  7275. }
  7276. }
  7277. this._observers = null;
  7278. this._observables = null;
  7279. };
  7280. /**
  7281. * Raise a callback when one of the observable will notify
  7282. * @param observables defines a list of observables to watch
  7283. * @param callback defines the callback to call on notification
  7284. * @param mask defines the mask used to filter notifications
  7285. * @param scope defines the current scope used to restore the JS context
  7286. * @returns the new MultiObserver
  7287. */
  7288. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7289. if (mask === void 0) { mask = -1; }
  7290. if (scope === void 0) { scope = null; }
  7291. var result = new MultiObserver();
  7292. result._observers = new Array();
  7293. result._observables = observables;
  7294. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7295. var observable = observables_1[_i];
  7296. var observer = observable.add(callback, mask, false, scope);
  7297. if (observer) {
  7298. result._observers.push(observer);
  7299. }
  7300. }
  7301. return result;
  7302. };
  7303. return MultiObserver;
  7304. }());
  7305. BABYLON.MultiObserver = MultiObserver;
  7306. /**
  7307. * The Observable class is a simple implementation of the Observable pattern.
  7308. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7309. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7310. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7311. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7312. */
  7313. var Observable = /** @class */ (function () {
  7314. /**
  7315. * Creates a new observable
  7316. * @param onObserverAdded defines a callback to call when a new observer is added
  7317. */
  7318. function Observable(onObserverAdded) {
  7319. this._observers = new Array();
  7320. this._eventState = new EventState(0);
  7321. if (onObserverAdded) {
  7322. this._onObserverAdded = onObserverAdded;
  7323. }
  7324. }
  7325. /**
  7326. * Create a new Observer with the specified callback
  7327. * @param callback the callback that will be executed for that Observer
  7328. * @param mask the mask used to filter observers
  7329. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7330. * @param scope optional scope for the callback to be called from
  7331. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7332. * @returns the new observer created for the callback
  7333. */
  7334. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7335. if (mask === void 0) { mask = -1; }
  7336. if (insertFirst === void 0) { insertFirst = false; }
  7337. if (scope === void 0) { scope = null; }
  7338. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7339. if (!callback) {
  7340. return null;
  7341. }
  7342. var observer = new Observer(callback, mask, scope);
  7343. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7344. if (insertFirst) {
  7345. this._observers.unshift(observer);
  7346. }
  7347. else {
  7348. this._observers.push(observer);
  7349. }
  7350. if (this._onObserverAdded) {
  7351. this._onObserverAdded(observer);
  7352. }
  7353. return observer;
  7354. };
  7355. /**
  7356. * Remove an Observer from the Observable object
  7357. * @param observer the instance of the Observer to remove
  7358. * @returns false if it doesn't belong to this Observable
  7359. */
  7360. Observable.prototype.remove = function (observer) {
  7361. if (!observer) {
  7362. return false;
  7363. }
  7364. var index = this._observers.indexOf(observer);
  7365. if (index !== -1) {
  7366. this._observers.splice(index, 1);
  7367. return true;
  7368. }
  7369. return false;
  7370. };
  7371. /**
  7372. * Remove a callback from the Observable object
  7373. * @param callback the callback to remove
  7374. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7375. * @returns false if it doesn't belong to this Observable
  7376. */
  7377. Observable.prototype.removeCallback = function (callback, scope) {
  7378. for (var index = 0; index < this._observers.length; index++) {
  7379. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7380. this._observers.splice(index, 1);
  7381. return true;
  7382. }
  7383. }
  7384. return false;
  7385. };
  7386. Observable.prototype._deferUnregister = function (observer) {
  7387. var _this = this;
  7388. observer.unregisterOnNextCall = false;
  7389. observer._willBeUnregistered = true;
  7390. BABYLON.Tools.SetImmediate(function () {
  7391. _this.remove(observer);
  7392. });
  7393. };
  7394. /**
  7395. * Notify all Observers by calling their respective callback with the given data
  7396. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7397. * @param eventData defines the data to send to all observers
  7398. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7399. * @param target defines the original target of the state
  7400. * @param currentTarget defines the current target of the state
  7401. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7402. */
  7403. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7404. if (mask === void 0) { mask = -1; }
  7405. if (!this._observers.length) {
  7406. return true;
  7407. }
  7408. var state = this._eventState;
  7409. state.mask = mask;
  7410. state.target = target;
  7411. state.currentTarget = currentTarget;
  7412. state.skipNextObservers = false;
  7413. state.lastReturnValue = eventData;
  7414. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7415. var obs = _a[_i];
  7416. if (obs._willBeUnregistered) {
  7417. continue;
  7418. }
  7419. if (obs.mask & mask) {
  7420. if (obs.scope) {
  7421. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7422. }
  7423. else {
  7424. state.lastReturnValue = obs.callback(eventData, state);
  7425. }
  7426. if (obs.unregisterOnNextCall) {
  7427. this._deferUnregister(obs);
  7428. }
  7429. }
  7430. if (state.skipNextObservers) {
  7431. return false;
  7432. }
  7433. }
  7434. return true;
  7435. };
  7436. /**
  7437. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7438. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7439. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7440. * and it is crucial that all callbacks will be executed.
  7441. * The order of the callbacks is kept, callbacks are not executed parallel.
  7442. *
  7443. * @param eventData The data to be sent to each callback
  7444. * @param mask is used to filter observers defaults to -1
  7445. * @param target defines the callback target (see EventState)
  7446. * @param currentTarget defines he current object in the bubbling phase
  7447. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7448. */
  7449. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7450. var _this = this;
  7451. if (mask === void 0) { mask = -1; }
  7452. // create an empty promise
  7453. var p = Promise.resolve(eventData);
  7454. // no observers? return this promise.
  7455. if (!this._observers.length) {
  7456. return p;
  7457. }
  7458. var state = this._eventState;
  7459. state.mask = mask;
  7460. state.target = target;
  7461. state.currentTarget = currentTarget;
  7462. state.skipNextObservers = false;
  7463. // execute one callback after another (not using Promise.all, the order is important)
  7464. this._observers.forEach(function (obs) {
  7465. if (state.skipNextObservers) {
  7466. return;
  7467. }
  7468. if (obs._willBeUnregistered) {
  7469. return;
  7470. }
  7471. if (obs.mask & mask) {
  7472. if (obs.scope) {
  7473. p = p.then(function (lastReturnedValue) {
  7474. state.lastReturnValue = lastReturnedValue;
  7475. return obs.callback.apply(obs.scope, [eventData, state]);
  7476. });
  7477. }
  7478. else {
  7479. p = p.then(function (lastReturnedValue) {
  7480. state.lastReturnValue = lastReturnedValue;
  7481. return obs.callback(eventData, state);
  7482. });
  7483. }
  7484. if (obs.unregisterOnNextCall) {
  7485. _this._deferUnregister(obs);
  7486. }
  7487. }
  7488. });
  7489. // return the eventData
  7490. return p.then(function () { return eventData; });
  7491. };
  7492. /**
  7493. * Notify a specific observer
  7494. * @param observer defines the observer to notify
  7495. * @param eventData defines the data to be sent to each callback
  7496. * @param mask is used to filter observers defaults to -1
  7497. */
  7498. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7499. if (mask === void 0) { mask = -1; }
  7500. var state = this._eventState;
  7501. state.mask = mask;
  7502. state.skipNextObservers = false;
  7503. observer.callback(eventData, state);
  7504. };
  7505. /**
  7506. * Gets a boolean indicating if the observable has at least one observer
  7507. * @returns true is the Observable has at least one Observer registered
  7508. */
  7509. Observable.prototype.hasObservers = function () {
  7510. return this._observers.length > 0;
  7511. };
  7512. /**
  7513. * Clear the list of observers
  7514. */
  7515. Observable.prototype.clear = function () {
  7516. this._observers = new Array();
  7517. this._onObserverAdded = null;
  7518. };
  7519. /**
  7520. * Clone the current observable
  7521. * @returns a new observable
  7522. */
  7523. Observable.prototype.clone = function () {
  7524. var result = new Observable();
  7525. result._observers = this._observers.slice(0);
  7526. return result;
  7527. };
  7528. /**
  7529. * Does this observable handles observer registered with a given mask
  7530. * @param mask defines the mask to be tested
  7531. * @return whether or not one observer registered with the given mask is handeled
  7532. **/
  7533. Observable.prototype.hasSpecificMask = function (mask) {
  7534. if (mask === void 0) { mask = -1; }
  7535. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7536. var obs = _a[_i];
  7537. if (obs.mask & mask || obs.mask === mask) {
  7538. return true;
  7539. }
  7540. }
  7541. return false;
  7542. };
  7543. return Observable;
  7544. }());
  7545. BABYLON.Observable = Observable;
  7546. })(BABYLON || (BABYLON = {}));
  7547. //# sourceMappingURL=babylon.observable.js.map
  7548. var BABYLON;
  7549. (function (BABYLON) {
  7550. var SmartArray = /** @class */ (function () {
  7551. function SmartArray(capacity) {
  7552. this.length = 0;
  7553. this.data = new Array(capacity);
  7554. this._id = SmartArray._GlobalId++;
  7555. }
  7556. SmartArray.prototype.push = function (value) {
  7557. this.data[this.length++] = value;
  7558. if (this.length > this.data.length) {
  7559. this.data.length *= 2;
  7560. }
  7561. };
  7562. SmartArray.prototype.forEach = function (func) {
  7563. for (var index = 0; index < this.length; index++) {
  7564. func(this.data[index]);
  7565. }
  7566. };
  7567. SmartArray.prototype.sort = function (compareFn) {
  7568. this.data.sort(compareFn);
  7569. };
  7570. SmartArray.prototype.reset = function () {
  7571. this.length = 0;
  7572. };
  7573. SmartArray.prototype.dispose = function () {
  7574. this.reset();
  7575. if (this.data) {
  7576. this.data.length = 0;
  7577. this.data = [];
  7578. }
  7579. };
  7580. SmartArray.prototype.concat = function (array) {
  7581. if (array.length === 0) {
  7582. return;
  7583. }
  7584. if (this.length + array.length > this.data.length) {
  7585. this.data.length = (this.length + array.length) * 2;
  7586. }
  7587. for (var index = 0; index < array.length; index++) {
  7588. this.data[this.length++] = (array.data || array)[index];
  7589. }
  7590. };
  7591. SmartArray.prototype.indexOf = function (value) {
  7592. var position = this.data.indexOf(value);
  7593. if (position >= this.length) {
  7594. return -1;
  7595. }
  7596. return position;
  7597. };
  7598. SmartArray.prototype.contains = function (value) {
  7599. return this.data.indexOf(value) !== -1;
  7600. };
  7601. // Statics
  7602. SmartArray._GlobalId = 0;
  7603. return SmartArray;
  7604. }());
  7605. BABYLON.SmartArray = SmartArray;
  7606. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7607. __extends(SmartArrayNoDuplicate, _super);
  7608. function SmartArrayNoDuplicate() {
  7609. var _this = _super !== null && _super.apply(this, arguments) || this;
  7610. _this._duplicateId = 0;
  7611. return _this;
  7612. }
  7613. SmartArrayNoDuplicate.prototype.push = function (value) {
  7614. _super.prototype.push.call(this, value);
  7615. if (!value.__smartArrayFlags) {
  7616. value.__smartArrayFlags = {};
  7617. }
  7618. value.__smartArrayFlags[this._id] = this._duplicateId;
  7619. };
  7620. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7621. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7622. return false;
  7623. }
  7624. this.push(value);
  7625. return true;
  7626. };
  7627. SmartArrayNoDuplicate.prototype.reset = function () {
  7628. _super.prototype.reset.call(this);
  7629. this._duplicateId++;
  7630. };
  7631. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7632. if (array.length === 0) {
  7633. return;
  7634. }
  7635. if (this.length + array.length > this.data.length) {
  7636. this.data.length = (this.length + array.length) * 2;
  7637. }
  7638. for (var index = 0; index < array.length; index++) {
  7639. var item = (array.data || array)[index];
  7640. this.pushNoDuplicate(item);
  7641. }
  7642. };
  7643. return SmartArrayNoDuplicate;
  7644. }(SmartArray));
  7645. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7646. })(BABYLON || (BABYLON = {}));
  7647. //# sourceMappingURL=babylon.smartArray.js.map
  7648. var BABYLON;
  7649. (function (BABYLON) {
  7650. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7651. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7652. var LoadFileError = /** @class */ (function (_super) {
  7653. __extends(LoadFileError, _super);
  7654. function LoadFileError(message, request) {
  7655. var _this = _super.call(this, message) || this;
  7656. _this.request = request;
  7657. _this.name = "LoadFileError";
  7658. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7659. return _this;
  7660. }
  7661. // Polyfill for Object.setPrototypeOf if necessary.
  7662. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7663. return LoadFileError;
  7664. }(Error));
  7665. BABYLON.LoadFileError = LoadFileError;
  7666. var RetryStrategy = /** @class */ (function () {
  7667. function RetryStrategy() {
  7668. }
  7669. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7670. if (maxRetries === void 0) { maxRetries = 3; }
  7671. if (baseInterval === void 0) { baseInterval = 500; }
  7672. return function (url, request, retryIndex) {
  7673. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7674. return -1;
  7675. }
  7676. return Math.pow(2, retryIndex) * baseInterval;
  7677. };
  7678. };
  7679. return RetryStrategy;
  7680. }());
  7681. BABYLON.RetryStrategy = RetryStrategy;
  7682. // Screenshots
  7683. var screenshotCanvas;
  7684. var cloneValue = function (source, destinationObject) {
  7685. if (!source)
  7686. return null;
  7687. if (source instanceof BABYLON.Mesh) {
  7688. return null;
  7689. }
  7690. if (source instanceof BABYLON.SubMesh) {
  7691. return source.clone(destinationObject);
  7692. }
  7693. else if (source.clone) {
  7694. return source.clone();
  7695. }
  7696. return null;
  7697. };
  7698. var Tools = /** @class */ (function () {
  7699. function Tools() {
  7700. }
  7701. /**
  7702. * Interpolates between a and b via alpha
  7703. * @param a The lower value (returned when alpha = 0)
  7704. * @param b The upper value (returned when alpha = 1)
  7705. * @param alpha The interpolation-factor
  7706. * @return The mixed value
  7707. */
  7708. Tools.Mix = function (a, b, alpha) {
  7709. return a * (1 - alpha) + b * alpha;
  7710. };
  7711. Tools.Instantiate = function (className) {
  7712. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7713. return Tools.RegisteredExternalClasses[className];
  7714. }
  7715. var arr = className.split(".");
  7716. var fn = (window || this);
  7717. for (var i = 0, len = arr.length; i < len; i++) {
  7718. fn = fn[arr[i]];
  7719. }
  7720. if (typeof fn !== "function") {
  7721. return null;
  7722. }
  7723. return fn;
  7724. };
  7725. /**
  7726. * Provides a slice function that will work even on IE
  7727. * @param data defines the array to slice
  7728. * @returns the new sliced array
  7729. */
  7730. Tools.Slice = function (data) {
  7731. if (data.slice) {
  7732. return data.slice();
  7733. }
  7734. return Array.prototype.slice.call(data);
  7735. };
  7736. Tools.SetImmediate = function (action) {
  7737. if (window.setImmediate) {
  7738. window.setImmediate(action);
  7739. }
  7740. else {
  7741. setTimeout(action, 1);
  7742. }
  7743. };
  7744. Tools.IsExponentOfTwo = function (value) {
  7745. var count = 1;
  7746. do {
  7747. count *= 2;
  7748. } while (count < value);
  7749. return count === value;
  7750. };
  7751. /**
  7752. * Find the next highest power of two.
  7753. * @param x Number to start search from.
  7754. * @return Next highest power of two.
  7755. */
  7756. Tools.CeilingPOT = function (x) {
  7757. x--;
  7758. x |= x >> 1;
  7759. x |= x >> 2;
  7760. x |= x >> 4;
  7761. x |= x >> 8;
  7762. x |= x >> 16;
  7763. x++;
  7764. return x;
  7765. };
  7766. /**
  7767. * Find the next lowest power of two.
  7768. * @param x Number to start search from.
  7769. * @return Next lowest power of two.
  7770. */
  7771. Tools.FloorPOT = function (x) {
  7772. x = x | (x >> 1);
  7773. x = x | (x >> 2);
  7774. x = x | (x >> 4);
  7775. x = x | (x >> 8);
  7776. x = x | (x >> 16);
  7777. return x - (x >> 1);
  7778. };
  7779. /**
  7780. * Find the nearest power of two.
  7781. * @param x Number to start search from.
  7782. * @return Next nearest power of two.
  7783. */
  7784. Tools.NearestPOT = function (x) {
  7785. var c = Tools.CeilingPOT(x);
  7786. var f = Tools.FloorPOT(x);
  7787. return (c - x) > (x - f) ? f : c;
  7788. };
  7789. Tools.GetExponentOfTwo = function (value, max, mode) {
  7790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7791. var pot;
  7792. switch (mode) {
  7793. case BABYLON.Engine.SCALEMODE_FLOOR:
  7794. pot = Tools.FloorPOT(value);
  7795. break;
  7796. case BABYLON.Engine.SCALEMODE_NEAREST:
  7797. pot = Tools.NearestPOT(value);
  7798. break;
  7799. case BABYLON.Engine.SCALEMODE_CEILING:
  7800. default:
  7801. pot = Tools.CeilingPOT(value);
  7802. break;
  7803. }
  7804. return Math.min(pot, max);
  7805. };
  7806. Tools.GetFilename = function (path) {
  7807. var index = path.lastIndexOf("/");
  7808. if (index < 0)
  7809. return path;
  7810. return path.substring(index + 1);
  7811. };
  7812. /**
  7813. * Extracts the "folder" part of a path (everything before the filename).
  7814. * @param uri The URI to extract the info from
  7815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7816. * @returns The "folder" part of the path
  7817. */
  7818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7820. var index = uri.lastIndexOf("/");
  7821. if (index < 0) {
  7822. if (returnUnchangedIfNoSlash) {
  7823. return uri;
  7824. }
  7825. return "";
  7826. }
  7827. return uri.substring(0, index + 1);
  7828. };
  7829. Tools.GetDOMTextContent = function (element) {
  7830. var result = "";
  7831. var child = element.firstChild;
  7832. while (child) {
  7833. if (child.nodeType === 3) {
  7834. result += child.textContent;
  7835. }
  7836. child = child.nextSibling;
  7837. }
  7838. return result;
  7839. };
  7840. Tools.ToDegrees = function (angle) {
  7841. return angle * 180 / Math.PI;
  7842. };
  7843. Tools.ToRadians = function (angle) {
  7844. return angle * Math.PI / 180;
  7845. };
  7846. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7847. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7848. var output = "";
  7849. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7850. var i = 0;
  7851. var bytes = new Uint8Array(buffer);
  7852. while (i < bytes.length) {
  7853. chr1 = bytes[i++];
  7854. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7855. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7856. enc1 = chr1 >> 2;
  7857. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7858. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7859. enc4 = chr3 & 63;
  7860. if (isNaN(chr2)) {
  7861. enc3 = enc4 = 64;
  7862. }
  7863. else if (isNaN(chr3)) {
  7864. enc4 = 64;
  7865. }
  7866. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7867. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7868. }
  7869. return "data:image/png;base64," + output;
  7870. };
  7871. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7872. if (bias === void 0) { bias = null; }
  7873. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7874. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7875. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7876. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7879. }
  7880. if (bias) {
  7881. minimum.x -= minimum.x * bias.x + bias.y;
  7882. minimum.y -= minimum.y * bias.x + bias.y;
  7883. minimum.z -= minimum.z * bias.x + bias.y;
  7884. maximum.x += maximum.x * bias.x + bias.y;
  7885. maximum.y += maximum.y * bias.x + bias.y;
  7886. maximum.z += maximum.z * bias.x + bias.y;
  7887. }
  7888. return {
  7889. minimum: minimum,
  7890. maximum: maximum
  7891. };
  7892. };
  7893. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7894. if (bias === void 0) { bias = null; }
  7895. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7896. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7897. if (!stride) {
  7898. stride = 3;
  7899. }
  7900. for (var index = start; index < start + count; index++) {
  7901. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.Vector2ArrayFeeder = function (array) {
  7919. return function (index) {
  7920. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7921. var length = isFloatArray ? array.length / 2 : array.length;
  7922. if (index >= length) {
  7923. return null;
  7924. }
  7925. if (isFloatArray) {
  7926. var fa = array;
  7927. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7928. }
  7929. var a = array;
  7930. return a[index];
  7931. };
  7932. };
  7933. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7934. if (bias === void 0) { bias = null; }
  7935. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7936. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7937. var i = 0;
  7938. var cur = feeder(i++);
  7939. while (cur) {
  7940. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7941. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7942. cur = feeder(i++);
  7943. }
  7944. if (bias) {
  7945. minimum.x -= minimum.x * bias.x + bias.y;
  7946. minimum.y -= minimum.y * bias.x + bias.y;
  7947. maximum.x += maximum.x * bias.x + bias.y;
  7948. maximum.y += maximum.y * bias.x + bias.y;
  7949. }
  7950. return {
  7951. minimum: minimum,
  7952. maximum: maximum
  7953. };
  7954. };
  7955. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7956. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7957. return null;
  7958. return Array.isArray(obj) ? obj : [obj];
  7959. };
  7960. // Misc.
  7961. Tools.GetPointerPrefix = function () {
  7962. var eventPrefix = "pointer";
  7963. // Check if pointer events are supported
  7964. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7965. eventPrefix = "mouse";
  7966. }
  7967. return eventPrefix;
  7968. };
  7969. /**
  7970. * @param func - the function to be called
  7971. * @param requester - the object that will request the next frame. Falls back to window.
  7972. */
  7973. Tools.QueueNewFrame = function (func, requester) {
  7974. if (!Tools.IsWindowObjectExist()) {
  7975. return setTimeout(func, 16);
  7976. }
  7977. if (!requester) {
  7978. requester = window;
  7979. }
  7980. if (requester.requestAnimationFrame) {
  7981. return requester.requestAnimationFrame(func);
  7982. }
  7983. else if (requester.msRequestAnimationFrame) {
  7984. return requester.msRequestAnimationFrame(func);
  7985. }
  7986. else if (requester.webkitRequestAnimationFrame) {
  7987. return requester.webkitRequestAnimationFrame(func);
  7988. }
  7989. else if (requester.mozRequestAnimationFrame) {
  7990. return requester.mozRequestAnimationFrame(func);
  7991. }
  7992. else if (requester.oRequestAnimationFrame) {
  7993. return requester.oRequestAnimationFrame(func);
  7994. }
  7995. else {
  7996. return window.setTimeout(func, 16);
  7997. }
  7998. };
  7999. Tools.RequestFullscreen = function (element) {
  8000. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8001. if (!requestFunction)
  8002. return;
  8003. requestFunction.call(element);
  8004. };
  8005. Tools.ExitFullscreen = function () {
  8006. if (document.exitFullscreen) {
  8007. document.exitFullscreen();
  8008. }
  8009. else if (document.mozCancelFullScreen) {
  8010. document.mozCancelFullScreen();
  8011. }
  8012. else if (document.webkitCancelFullScreen) {
  8013. document.webkitCancelFullScreen();
  8014. }
  8015. else if (document.msCancelFullScreen) {
  8016. document.msCancelFullScreen();
  8017. }
  8018. };
  8019. Tools.SetCorsBehavior = function (url, element) {
  8020. if (url && url.indexOf("data:") === 0) {
  8021. return;
  8022. }
  8023. if (Tools.CorsBehavior) {
  8024. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8025. element.crossOrigin = Tools.CorsBehavior;
  8026. }
  8027. else {
  8028. var result = Tools.CorsBehavior(url);
  8029. if (result) {
  8030. element.crossOrigin = result;
  8031. }
  8032. }
  8033. }
  8034. };
  8035. // External files
  8036. Tools.CleanUrl = function (url) {
  8037. url = url.replace(/#/mg, "%23");
  8038. return url;
  8039. };
  8040. Tools.LoadImage = function (url, onLoad, onError, database) {
  8041. if (url instanceof ArrayBuffer) {
  8042. url = Tools.EncodeArrayBufferTobase64(url);
  8043. }
  8044. url = Tools.CleanUrl(url);
  8045. url = Tools.PreprocessUrl(url);
  8046. var img = new Image();
  8047. Tools.SetCorsBehavior(url, img);
  8048. var loadHandler = function () {
  8049. img.removeEventListener("load", loadHandler);
  8050. img.removeEventListener("error", errorHandler);
  8051. onLoad(img);
  8052. };
  8053. var errorHandler = function (err) {
  8054. img.removeEventListener("load", loadHandler);
  8055. img.removeEventListener("error", errorHandler);
  8056. Tools.Error("Error while trying to load image: " + url);
  8057. if (onError) {
  8058. onError("Error while trying to load image: " + url, err);
  8059. }
  8060. };
  8061. img.addEventListener("load", loadHandler);
  8062. img.addEventListener("error", errorHandler);
  8063. var noIndexedDB = function () {
  8064. img.src = url;
  8065. };
  8066. var loadFromIndexedDB = function () {
  8067. if (database) {
  8068. database.loadImageFromDB(url, img);
  8069. }
  8070. };
  8071. //ANY database to do!
  8072. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8073. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8074. }
  8075. else {
  8076. if (url.indexOf("file:") !== -1) {
  8077. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8078. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8079. try {
  8080. var blobURL;
  8081. try {
  8082. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8083. }
  8084. catch (ex) {
  8085. // Chrome doesn't support oneTimeOnly parameter
  8086. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8087. }
  8088. img.src = blobURL;
  8089. }
  8090. catch (e) {
  8091. img.src = "";
  8092. }
  8093. return img;
  8094. }
  8095. }
  8096. noIndexedDB();
  8097. }
  8098. return img;
  8099. };
  8100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8101. url = Tools.CleanUrl(url);
  8102. url = Tools.PreprocessUrl(url);
  8103. // If file and file input are set
  8104. if (url.indexOf("file:") !== -1) {
  8105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8108. }
  8109. }
  8110. var loadUrl = Tools.BaseUrl + url;
  8111. var aborted = false;
  8112. var fileRequest = {
  8113. onCompleteObservable: new BABYLON.Observable(),
  8114. abort: function () { return aborted = true; },
  8115. };
  8116. var requestFile = function () {
  8117. var request = new XMLHttpRequest();
  8118. var retryHandle = null;
  8119. fileRequest.abort = function () {
  8120. aborted = true;
  8121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8122. request.abort();
  8123. }
  8124. if (retryHandle !== null) {
  8125. clearTimeout(retryHandle);
  8126. retryHandle = null;
  8127. }
  8128. };
  8129. var retryLoop = function (retryIndex) {
  8130. request.open('GET', loadUrl, true);
  8131. if (useArrayBuffer) {
  8132. request.responseType = "arraybuffer";
  8133. }
  8134. if (onProgress) {
  8135. request.addEventListener("progress", onProgress);
  8136. }
  8137. var onLoadEnd = function () {
  8138. request.removeEventListener("loadend", onLoadEnd);
  8139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8140. fileRequest.onCompleteObservable.clear();
  8141. };
  8142. request.addEventListener("loadend", onLoadEnd);
  8143. var onReadyStateChange = function () {
  8144. if (aborted) {
  8145. return;
  8146. }
  8147. // In case of undefined state in some browsers.
  8148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8150. request.removeEventListener("readystatechange", onReadyStateChange);
  8151. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8153. return;
  8154. }
  8155. var retryStrategy = Tools.DefaultRetryStrategy;
  8156. if (retryStrategy) {
  8157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8158. if (waitTime !== -1) {
  8159. // Prevent the request from completing for retry.
  8160. request.removeEventListener("loadend", onLoadEnd);
  8161. request = new XMLHttpRequest();
  8162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8163. return;
  8164. }
  8165. }
  8166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8167. if (onError) {
  8168. onError(request, e);
  8169. }
  8170. else {
  8171. throw e;
  8172. }
  8173. }
  8174. };
  8175. request.addEventListener("readystatechange", onReadyStateChange);
  8176. request.send();
  8177. };
  8178. retryLoop(0);
  8179. };
  8180. // Caching all files
  8181. if (database && database.enableSceneOffline) {
  8182. var noIndexedDB_1 = function () {
  8183. if (!aborted) {
  8184. requestFile();
  8185. }
  8186. };
  8187. var loadFromIndexedDB = function () {
  8188. // TODO: database needs to support aborting and should return a IFileRequest
  8189. if (aborted) {
  8190. return;
  8191. }
  8192. if (database) {
  8193. database.loadFileFromDB(url, function (data) {
  8194. if (!aborted) {
  8195. onSuccess(data);
  8196. }
  8197. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8198. }, onProgress ? function (event) {
  8199. if (!aborted) {
  8200. onProgress(event);
  8201. }
  8202. } : undefined, noIndexedDB_1, useArrayBuffer);
  8203. }
  8204. };
  8205. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8206. }
  8207. else {
  8208. requestFile();
  8209. }
  8210. return fileRequest;
  8211. };
  8212. /**
  8213. * Load a script (identified by an url). When the url returns, the
  8214. * content of this file is added into a new script element, attached to the DOM (body element)
  8215. */
  8216. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8217. var head = document.getElementsByTagName('head')[0];
  8218. var script = document.createElement('script');
  8219. script.type = 'text/javascript';
  8220. script.src = scriptUrl;
  8221. script.onload = function () {
  8222. if (onSuccess) {
  8223. onSuccess();
  8224. }
  8225. };
  8226. script.onerror = function (e) {
  8227. if (onError) {
  8228. onError("Unable to load script", e);
  8229. }
  8230. };
  8231. head.appendChild(script);
  8232. };
  8233. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8234. var reader = new FileReader();
  8235. var request = {
  8236. onCompleteObservable: new BABYLON.Observable(),
  8237. abort: function () { return reader.abort(); },
  8238. };
  8239. reader.onloadend = function (e) {
  8240. request.onCompleteObservable.notifyObservers(request);
  8241. };
  8242. reader.onload = function (e) {
  8243. //target doesn't have result from ts 1.3
  8244. callback(e.target['result']);
  8245. };
  8246. reader.onprogress = progressCallback;
  8247. reader.readAsDataURL(fileToLoad);
  8248. return request;
  8249. };
  8250. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8251. var reader = new FileReader();
  8252. var request = {
  8253. onCompleteObservable: new BABYLON.Observable(),
  8254. abort: function () { return reader.abort(); },
  8255. };
  8256. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8257. reader.onerror = function (e) {
  8258. Tools.Log("Error while reading file: " + fileToLoad.name);
  8259. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8260. };
  8261. reader.onload = function (e) {
  8262. //target doesn't have result from ts 1.3
  8263. callback(e.target['result']);
  8264. };
  8265. if (progressCallBack) {
  8266. reader.onprogress = progressCallBack;
  8267. }
  8268. if (!useArrayBuffer) {
  8269. // Asynchronous read
  8270. reader.readAsText(fileToLoad);
  8271. }
  8272. else {
  8273. reader.readAsArrayBuffer(fileToLoad);
  8274. }
  8275. return request;
  8276. };
  8277. //returns a downloadable url to a file content.
  8278. Tools.FileAsURL = function (content) {
  8279. var fileBlob = new Blob([content]);
  8280. var url = window.URL || window.webkitURL;
  8281. var link = url.createObjectURL(fileBlob);
  8282. return link;
  8283. };
  8284. // Misc.
  8285. Tools.Format = function (value, decimals) {
  8286. if (decimals === void 0) { decimals = 2; }
  8287. return value.toFixed(decimals);
  8288. };
  8289. Tools.CheckExtends = function (v, min, max) {
  8290. if (v.x < min.x)
  8291. min.x = v.x;
  8292. if (v.y < min.y)
  8293. min.y = v.y;
  8294. if (v.z < min.z)
  8295. min.z = v.z;
  8296. if (v.x > max.x)
  8297. max.x = v.x;
  8298. if (v.y > max.y)
  8299. max.y = v.y;
  8300. if (v.z > max.z)
  8301. max.z = v.z;
  8302. };
  8303. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8304. for (var prop in source) {
  8305. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8306. continue;
  8307. }
  8308. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8309. continue;
  8310. }
  8311. var sourceValue = source[prop];
  8312. var typeOfSourceValue = typeof sourceValue;
  8313. if (typeOfSourceValue === "function") {
  8314. continue;
  8315. }
  8316. if (typeOfSourceValue === "object") {
  8317. if (sourceValue instanceof Array) {
  8318. destination[prop] = [];
  8319. if (sourceValue.length > 0) {
  8320. if (typeof sourceValue[0] == "object") {
  8321. for (var index = 0; index < sourceValue.length; index++) {
  8322. var clonedValue = cloneValue(sourceValue[index], destination);
  8323. if (destination[prop].indexOf(clonedValue) === -1) {
  8324. destination[prop].push(clonedValue);
  8325. }
  8326. }
  8327. }
  8328. else {
  8329. destination[prop] = sourceValue.slice(0);
  8330. }
  8331. }
  8332. }
  8333. else {
  8334. destination[prop] = cloneValue(sourceValue, destination);
  8335. }
  8336. }
  8337. else {
  8338. destination[prop] = sourceValue;
  8339. }
  8340. }
  8341. };
  8342. Tools.IsEmpty = function (obj) {
  8343. for (var i in obj) {
  8344. if (obj.hasOwnProperty(i)) {
  8345. return false;
  8346. }
  8347. }
  8348. return true;
  8349. };
  8350. Tools.RegisterTopRootEvents = function (events) {
  8351. for (var index = 0; index < events.length; index++) {
  8352. var event = events[index];
  8353. window.addEventListener(event.name, event.handler, false);
  8354. try {
  8355. if (window.parent) {
  8356. window.parent.addEventListener(event.name, event.handler, false);
  8357. }
  8358. }
  8359. catch (e) {
  8360. // Silently fails...
  8361. }
  8362. }
  8363. };
  8364. Tools.UnregisterTopRootEvents = function (events) {
  8365. for (var index = 0; index < events.length; index++) {
  8366. var event = events[index];
  8367. window.removeEventListener(event.name, event.handler);
  8368. try {
  8369. if (window.parent) {
  8370. window.parent.removeEventListener(event.name, event.handler);
  8371. }
  8372. }
  8373. catch (e) {
  8374. // Silently fails...
  8375. }
  8376. }
  8377. };
  8378. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8379. if (mimeType === void 0) { mimeType = "image/png"; }
  8380. // Read the contents of the framebuffer
  8381. var numberOfChannelsByLine = width * 4;
  8382. var halfHeight = height / 2;
  8383. //Reading datas from WebGL
  8384. var data = engine.readPixels(0, 0, width, height);
  8385. //To flip image on Y axis.
  8386. for (var i = 0; i < halfHeight; i++) {
  8387. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8388. var currentCell = j + i * numberOfChannelsByLine;
  8389. var targetLine = height - i - 1;
  8390. var targetCell = j + targetLine * numberOfChannelsByLine;
  8391. var temp = data[currentCell];
  8392. data[currentCell] = data[targetCell];
  8393. data[targetCell] = temp;
  8394. }
  8395. }
  8396. // Create a 2D canvas to store the result
  8397. if (!screenshotCanvas) {
  8398. screenshotCanvas = document.createElement('canvas');
  8399. }
  8400. screenshotCanvas.width = width;
  8401. screenshotCanvas.height = height;
  8402. var context = screenshotCanvas.getContext('2d');
  8403. if (context) {
  8404. // Copy the pixels to a 2D canvas
  8405. var imageData = context.createImageData(width, height);
  8406. var castData = (imageData.data);
  8407. castData.set(data);
  8408. context.putImageData(imageData, 0, 0);
  8409. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8410. }
  8411. };
  8412. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8413. if (mimeType === void 0) { mimeType = "image/png"; }
  8414. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8415. if (successCallback) {
  8416. successCallback(base64Image);
  8417. }
  8418. else {
  8419. // We need HTMLCanvasElement.toBlob for HD screenshots
  8420. if (!screenshotCanvas.toBlob) {
  8421. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8422. screenshotCanvas.toBlob = function (callback, type, quality) {
  8423. var _this = this;
  8424. setTimeout(function () {
  8425. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8426. for (var i = 0; i < len; i++) {
  8427. arr[i] = binStr.charCodeAt(i);
  8428. }
  8429. callback(new Blob([arr], { type: type || 'image/png' }));
  8430. });
  8431. };
  8432. }
  8433. screenshotCanvas.toBlob(function (blob) {
  8434. var url = URL.createObjectURL(blob);
  8435. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8436. if (("download" in document.createElement("a"))) {
  8437. var a = window.document.createElement("a");
  8438. a.href = url;
  8439. if (fileName) {
  8440. a.setAttribute("download", fileName);
  8441. }
  8442. else {
  8443. var date = new Date();
  8444. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8445. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8446. }
  8447. window.document.body.appendChild(a);
  8448. a.addEventListener("click", function () {
  8449. if (a.parentElement) {
  8450. a.parentElement.removeChild(a);
  8451. }
  8452. });
  8453. a.click();
  8454. }
  8455. else {
  8456. var newWindow = window.open("");
  8457. if (!newWindow)
  8458. return;
  8459. var img = newWindow.document.createElement("img");
  8460. img.onload = function () {
  8461. // no longer need to read the blob so it's revoked
  8462. URL.revokeObjectURL(url);
  8463. };
  8464. img.src = url;
  8465. newWindow.document.body.appendChild(img);
  8466. }
  8467. });
  8468. }
  8469. };
  8470. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8471. if (mimeType === void 0) { mimeType = "image/png"; }
  8472. var width;
  8473. var height;
  8474. // If a precision value is specified
  8475. if (size.precision) {
  8476. width = Math.round(engine.getRenderWidth() * size.precision);
  8477. height = Math.round(width / engine.getAspectRatio(camera));
  8478. }
  8479. else if (size.width && size.height) {
  8480. width = size.width;
  8481. height = size.height;
  8482. }
  8483. else if (size.width && !size.height) {
  8484. width = size.width;
  8485. height = Math.round(width / engine.getAspectRatio(camera));
  8486. }
  8487. else if (size.height && !size.width) {
  8488. height = size.height;
  8489. width = Math.round(height * engine.getAspectRatio(camera));
  8490. }
  8491. else if (!isNaN(size)) {
  8492. height = size;
  8493. width = size;
  8494. }
  8495. else {
  8496. Tools.Error("Invalid 'size' parameter !");
  8497. return;
  8498. }
  8499. if (!screenshotCanvas) {
  8500. screenshotCanvas = document.createElement('canvas');
  8501. }
  8502. screenshotCanvas.width = width;
  8503. screenshotCanvas.height = height;
  8504. var renderContext = screenshotCanvas.getContext("2d");
  8505. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8506. var newWidth = width;
  8507. var newHeight = newWidth / ratio;
  8508. if (newHeight > height) {
  8509. newHeight = height;
  8510. newWidth = newHeight * ratio;
  8511. }
  8512. var offsetX = Math.max(0, width - newWidth) / 2;
  8513. var offsetY = Math.max(0, height - newHeight) / 2;
  8514. var renderingCanvas = engine.getRenderingCanvas();
  8515. if (renderContext && renderingCanvas) {
  8516. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8517. }
  8518. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8519. };
  8520. /**
  8521. * Generates an image screenshot from the specified camera.
  8522. *
  8523. * @param engine The engine to use for rendering
  8524. * @param camera The camera to use for rendering
  8525. * @param size This parameter can be set to a single number or to an object with the
  8526. * following (optional) properties: precision, width, height. If a single number is passed,
  8527. * it will be used for both width and height. If an object is passed, the screenshot size
  8528. * will be derived from the parameters. The precision property is a multiplier allowing
  8529. * rendering at a higher or lower resolution.
  8530. * @param successCallback The callback receives a single parameter which contains the
  8531. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8532. * src parameter of an <img> to display it.
  8533. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8534. * Check your browser for supported MIME types.
  8535. * @param samples Texture samples (default: 1)
  8536. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8537. * @param fileName A name for for the downloaded file.
  8538. * @constructor
  8539. */
  8540. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. if (samples === void 0) { samples = 1; }
  8543. if (antialiasing === void 0) { antialiasing = false; }
  8544. var width;
  8545. var height;
  8546. //If a precision value is specified
  8547. if (size.precision) {
  8548. width = Math.round(engine.getRenderWidth() * size.precision);
  8549. height = Math.round(width / engine.getAspectRatio(camera));
  8550. size = { width: width, height: height };
  8551. }
  8552. else if (size.width && size.height) {
  8553. width = size.width;
  8554. height = size.height;
  8555. }
  8556. else if (size.width && !size.height) {
  8557. width = size.width;
  8558. height = Math.round(width / engine.getAspectRatio(camera));
  8559. size = { width: width, height: height };
  8560. }
  8561. else if (size.height && !size.width) {
  8562. height = size.height;
  8563. width = Math.round(height * engine.getAspectRatio(camera));
  8564. size = { width: width, height: height };
  8565. }
  8566. else if (!isNaN(size)) {
  8567. height = size;
  8568. width = size;
  8569. }
  8570. else {
  8571. Tools.Error("Invalid 'size' parameter !");
  8572. return;
  8573. }
  8574. var scene = camera.getScene();
  8575. var previousCamera = null;
  8576. if (scene.activeCamera !== camera) {
  8577. previousCamera = scene.activeCamera;
  8578. scene.activeCamera = camera;
  8579. }
  8580. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8581. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8582. texture.renderList = null;
  8583. texture.samples = samples;
  8584. if (antialiasing) {
  8585. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8586. }
  8587. texture.onAfterRenderObservable.add(function () {
  8588. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8589. });
  8590. scene.incrementRenderId();
  8591. scene.resetCachedMaterial();
  8592. texture.render(true);
  8593. texture.dispose();
  8594. if (previousCamera) {
  8595. scene.activeCamera = previousCamera;
  8596. }
  8597. camera.getProjectionMatrix(true); // Force cache refresh;
  8598. };
  8599. // XHR response validator for local file scenario
  8600. Tools.ValidateXHRData = function (xhr, dataType) {
  8601. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8602. if (dataType === void 0) { dataType = 7; }
  8603. try {
  8604. if (dataType & 1) {
  8605. if (xhr.responseText && xhr.responseText.length > 0) {
  8606. return true;
  8607. }
  8608. else if (dataType === 1) {
  8609. return false;
  8610. }
  8611. }
  8612. if (dataType & 2) {
  8613. // Check header width and height since there is no "TGA" magic number
  8614. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8615. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8616. return true;
  8617. }
  8618. else if (dataType === 2) {
  8619. return false;
  8620. }
  8621. }
  8622. if (dataType & 4) {
  8623. // Check for the "DDS" magic number
  8624. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8625. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8626. return true;
  8627. }
  8628. else {
  8629. return false;
  8630. }
  8631. }
  8632. }
  8633. catch (e) {
  8634. // Global protection
  8635. }
  8636. return false;
  8637. };
  8638. /**
  8639. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8640. * Be aware Math.random() could cause collisions, but:
  8641. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  8642. */
  8643. Tools.RandomId = function () {
  8644. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8645. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8646. return v.toString(16);
  8647. });
  8648. };
  8649. /**
  8650. * Test if the given uri is a base64 string.
  8651. * @param uri The uri to test
  8652. * @return True if the uri is a base64 string or false otherwise.
  8653. */
  8654. Tools.IsBase64 = function (uri) {
  8655. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8656. };
  8657. /**
  8658. * Decode the given base64 uri.
  8659. * @param uri The uri to decode
  8660. * @return The decoded base64 data.
  8661. */
  8662. Tools.DecodeBase64 = function (uri) {
  8663. var decodedString = atob(uri.split(",")[1]);
  8664. var bufferLength = decodedString.length;
  8665. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8666. for (var i = 0; i < bufferLength; i++) {
  8667. bufferView[i] = decodedString.charCodeAt(i);
  8668. }
  8669. return bufferView.buffer;
  8670. };
  8671. Object.defineProperty(Tools, "NoneLogLevel", {
  8672. get: function () {
  8673. return Tools._NoneLogLevel;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(Tools, "MessageLogLevel", {
  8679. get: function () {
  8680. return Tools._MessageLogLevel;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(Tools, "WarningLogLevel", {
  8686. get: function () {
  8687. return Tools._WarningLogLevel;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Tools, "ErrorLogLevel", {
  8693. get: function () {
  8694. return Tools._ErrorLogLevel;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Tools, "AllLogLevel", {
  8700. get: function () {
  8701. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Tools._AddLogEntry = function (entry) {
  8707. Tools._LogCache = entry + Tools._LogCache;
  8708. if (Tools.OnNewCacheEntry) {
  8709. Tools.OnNewCacheEntry(entry);
  8710. }
  8711. };
  8712. Tools._FormatMessage = function (message) {
  8713. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8714. var date = new Date();
  8715. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8716. };
  8717. Tools._LogDisabled = function (message) {
  8718. // nothing to do
  8719. };
  8720. Tools._LogEnabled = function (message) {
  8721. var formattedMessage = Tools._FormatMessage(message);
  8722. console.log("BJS - " + formattedMessage);
  8723. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8724. Tools._AddLogEntry(entry);
  8725. };
  8726. Tools._WarnDisabled = function (message) {
  8727. // nothing to do
  8728. };
  8729. Tools._WarnEnabled = function (message) {
  8730. var formattedMessage = Tools._FormatMessage(message);
  8731. console.warn("BJS - " + formattedMessage);
  8732. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8733. Tools._AddLogEntry(entry);
  8734. };
  8735. Tools._ErrorDisabled = function (message) {
  8736. // nothing to do
  8737. };
  8738. Tools._ErrorEnabled = function (message) {
  8739. Tools.errorsCount++;
  8740. var formattedMessage = Tools._FormatMessage(message);
  8741. console.error("BJS - " + formattedMessage);
  8742. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8743. Tools._AddLogEntry(entry);
  8744. };
  8745. Object.defineProperty(Tools, "LogCache", {
  8746. get: function () {
  8747. return Tools._LogCache;
  8748. },
  8749. enumerable: true,
  8750. configurable: true
  8751. });
  8752. Tools.ClearLogCache = function () {
  8753. Tools._LogCache = "";
  8754. Tools.errorsCount = 0;
  8755. };
  8756. Object.defineProperty(Tools, "LogLevels", {
  8757. set: function (level) {
  8758. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8759. Tools.Log = Tools._LogEnabled;
  8760. }
  8761. else {
  8762. Tools.Log = Tools._LogDisabled;
  8763. }
  8764. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8765. Tools.Warn = Tools._WarnEnabled;
  8766. }
  8767. else {
  8768. Tools.Warn = Tools._WarnDisabled;
  8769. }
  8770. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8771. Tools.Error = Tools._ErrorEnabled;
  8772. }
  8773. else {
  8774. Tools.Error = Tools._ErrorDisabled;
  8775. }
  8776. },
  8777. enumerable: true,
  8778. configurable: true
  8779. });
  8780. Tools.IsWindowObjectExist = function () {
  8781. return (typeof window) !== "undefined";
  8782. };
  8783. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8784. get: function () {
  8785. return Tools._PerformanceNoneLogLevel;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8791. get: function () {
  8792. return Tools._PerformanceUserMarkLogLevel;
  8793. },
  8794. enumerable: true,
  8795. configurable: true
  8796. });
  8797. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8798. get: function () {
  8799. return Tools._PerformanceConsoleLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8805. set: function (level) {
  8806. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8807. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8808. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8809. return;
  8810. }
  8811. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8812. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8813. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8814. return;
  8815. }
  8816. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8817. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8823. };
  8824. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8825. };
  8826. Tools._StartUserMark = function (counterName, condition) {
  8827. if (condition === void 0) { condition = true; }
  8828. if (!Tools._performance) {
  8829. if (!Tools.IsWindowObjectExist()) {
  8830. return;
  8831. }
  8832. Tools._performance = window.performance;
  8833. }
  8834. if (!condition || !Tools._performance.mark) {
  8835. return;
  8836. }
  8837. Tools._performance.mark(counterName + "-Begin");
  8838. };
  8839. Tools._EndUserMark = function (counterName, condition) {
  8840. if (condition === void 0) { condition = true; }
  8841. if (!condition || !Tools._performance.mark) {
  8842. return;
  8843. }
  8844. Tools._performance.mark(counterName + "-End");
  8845. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8846. };
  8847. Tools._StartPerformanceConsole = function (counterName, condition) {
  8848. if (condition === void 0) { condition = true; }
  8849. if (!condition) {
  8850. return;
  8851. }
  8852. Tools._StartUserMark(counterName, condition);
  8853. if (console.time) {
  8854. console.time(counterName);
  8855. }
  8856. };
  8857. Tools._EndPerformanceConsole = function (counterName, condition) {
  8858. if (condition === void 0) { condition = true; }
  8859. if (!condition) {
  8860. return;
  8861. }
  8862. Tools._EndUserMark(counterName, condition);
  8863. if (console.time) {
  8864. console.timeEnd(counterName);
  8865. }
  8866. };
  8867. Object.defineProperty(Tools, "Now", {
  8868. get: function () {
  8869. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8870. return window.performance.now();
  8871. }
  8872. return new Date().getTime();
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. /**
  8878. * This method will return the name of the class used to create the instance of the given object.
  8879. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8880. * @param object the object to get the class name from
  8881. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8882. */
  8883. Tools.GetClassName = function (object, isType) {
  8884. if (isType === void 0) { isType = false; }
  8885. var name = null;
  8886. if (!isType && object.getClassName) {
  8887. name = object.getClassName();
  8888. }
  8889. else {
  8890. if (object instanceof Object) {
  8891. var classObj = isType ? object : Object.getPrototypeOf(object);
  8892. name = classObj.constructor["__bjsclassName__"];
  8893. }
  8894. if (!name) {
  8895. name = typeof object;
  8896. }
  8897. }
  8898. return name;
  8899. };
  8900. Tools.First = function (array, predicate) {
  8901. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8902. var el = array_1[_i];
  8903. if (predicate(el)) {
  8904. return el;
  8905. }
  8906. }
  8907. return null;
  8908. };
  8909. /**
  8910. * This method will return the name of the full name of the class, including its owning module (if any).
  8911. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  8912. * @param object the object to get the class name from
  8913. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  8914. */
  8915. Tools.getFullClassName = function (object, isType) {
  8916. if (isType === void 0) { isType = false; }
  8917. var className = null;
  8918. var moduleName = null;
  8919. if (!isType && object.getClassName) {
  8920. className = object.getClassName();
  8921. }
  8922. else {
  8923. if (object instanceof Object) {
  8924. var classObj = isType ? object : Object.getPrototypeOf(object);
  8925. className = classObj.constructor["__bjsclassName__"];
  8926. moduleName = classObj.constructor["__bjsmoduleName__"];
  8927. }
  8928. if (!className) {
  8929. className = typeof object;
  8930. }
  8931. }
  8932. if (!className) {
  8933. return null;
  8934. }
  8935. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8936. };
  8937. /**
  8938. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  8939. * @param array
  8940. */
  8941. Tools.arrayOrStringFeeder = function (array) {
  8942. return function (index) {
  8943. if (index >= array.length) {
  8944. return null;
  8945. }
  8946. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8947. if (val && val.getHashCode) {
  8948. val = val.getHashCode();
  8949. }
  8950. if (typeof val === "string") {
  8951. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8952. }
  8953. return val;
  8954. };
  8955. };
  8956. /**
  8957. * Compute the hashCode of a stream of number
  8958. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8959. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8960. * @return the hash code computed
  8961. */
  8962. Tools.hashCodeFromStream = function (feeder) {
  8963. // Based from here: http://stackoverflow.com/a/7616484/802124
  8964. var hash = 0;
  8965. var index = 0;
  8966. var chr = feeder(index++);
  8967. while (chr != null) {
  8968. hash = ((hash << 5) - hash) + chr;
  8969. hash |= 0; // Convert to 32bit integer
  8970. chr = feeder(index++);
  8971. }
  8972. return hash;
  8973. };
  8974. /**
  8975. * Returns a promise that resolves after the given amount of time.
  8976. * @param delay Number of milliseconds to delay
  8977. * @returns Promise that resolves after the given amount of time
  8978. */
  8979. Tools.DelayAsync = function (delay) {
  8980. return new Promise(function (resolve) {
  8981. setTimeout(function () {
  8982. resolve();
  8983. }, delay);
  8984. });
  8985. };
  8986. Tools.BaseUrl = "";
  8987. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8988. /**
  8989. * Default behaviour for cors in the application.
  8990. * It can be a string if the expected behavior is identical in the entire app.
  8991. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8992. */
  8993. Tools.CorsBehavior = "anonymous";
  8994. Tools.UseFallbackTexture = true;
  8995. /**
  8996. * Use this object to register external classes like custom textures or material
  8997. * to allow the laoders to instantiate them
  8998. */
  8999. Tools.RegisteredExternalClasses = {};
  9000. // Used in case of a texture loading problem
  9001. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9002. Tools.PreprocessUrl = function (url) {
  9003. return url;
  9004. };
  9005. // Logs
  9006. Tools._NoneLogLevel = 0;
  9007. Tools._MessageLogLevel = 1;
  9008. Tools._WarningLogLevel = 2;
  9009. Tools._ErrorLogLevel = 4;
  9010. Tools._LogCache = "";
  9011. Tools.errorsCount = 0;
  9012. Tools.Log = Tools._LogEnabled;
  9013. Tools.Warn = Tools._WarnEnabled;
  9014. Tools.Error = Tools._ErrorEnabled;
  9015. // Performances
  9016. Tools._PerformanceNoneLogLevel = 0;
  9017. Tools._PerformanceUserMarkLogLevel = 1;
  9018. Tools._PerformanceConsoleLogLevel = 2;
  9019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9021. return Tools;
  9022. }());
  9023. BABYLON.Tools = Tools;
  9024. /**
  9025. * This class is used to track a performance counter which is number based.
  9026. * The user has access to many properties which give statistics of different nature
  9027. *
  9028. * The implementer can track two kinds of Performance Counter: time and count
  9029. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9030. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9031. */
  9032. var PerfCounter = /** @class */ (function () {
  9033. function PerfCounter() {
  9034. this._startMonitoringTime = 0;
  9035. this._min = 0;
  9036. this._max = 0;
  9037. this._average = 0;
  9038. this._lastSecAverage = 0;
  9039. this._current = 0;
  9040. this._totalValueCount = 0;
  9041. this._totalAccumulated = 0;
  9042. this._lastSecAccumulated = 0;
  9043. this._lastSecTime = 0;
  9044. this._lastSecValueCount = 0;
  9045. }
  9046. Object.defineProperty(PerfCounter.prototype, "min", {
  9047. /**
  9048. * Returns the smallest value ever
  9049. */
  9050. get: function () {
  9051. return this._min;
  9052. },
  9053. enumerable: true,
  9054. configurable: true
  9055. });
  9056. Object.defineProperty(PerfCounter.prototype, "max", {
  9057. /**
  9058. * Returns the biggest value ever
  9059. */
  9060. get: function () {
  9061. return this._max;
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. Object.defineProperty(PerfCounter.prototype, "average", {
  9067. /**
  9068. * Returns the average value since the performance counter is running
  9069. */
  9070. get: function () {
  9071. return this._average;
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9077. /**
  9078. * Returns the average value of the last second the counter was monitored
  9079. */
  9080. get: function () {
  9081. return this._lastSecAverage;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(PerfCounter.prototype, "current", {
  9087. /**
  9088. * Returns the current value
  9089. */
  9090. get: function () {
  9091. return this._current;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(PerfCounter.prototype, "total", {
  9097. get: function () {
  9098. return this._totalAccumulated;
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Object.defineProperty(PerfCounter.prototype, "count", {
  9104. get: function () {
  9105. return this._totalValueCount;
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. /**
  9111. * Call this method to start monitoring a new frame.
  9112. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9113. */
  9114. PerfCounter.prototype.fetchNewFrame = function () {
  9115. this._totalValueCount++;
  9116. this._current = 0;
  9117. this._lastSecValueCount++;
  9118. };
  9119. /**
  9120. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9121. * @param newCount the count value to add to the monitored count
  9122. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9123. */
  9124. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9125. if (!PerfCounter.Enabled) {
  9126. return;
  9127. }
  9128. this._current += newCount;
  9129. if (fetchResult) {
  9130. this._fetchResult();
  9131. }
  9132. };
  9133. /**
  9134. * Start monitoring this performance counter
  9135. */
  9136. PerfCounter.prototype.beginMonitoring = function () {
  9137. if (!PerfCounter.Enabled) {
  9138. return;
  9139. }
  9140. this._startMonitoringTime = Tools.Now;
  9141. };
  9142. /**
  9143. * Compute the time lapsed since the previous beginMonitoring() call.
  9144. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9145. */
  9146. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9147. if (newFrame === void 0) { newFrame = true; }
  9148. if (!PerfCounter.Enabled) {
  9149. return;
  9150. }
  9151. if (newFrame) {
  9152. this.fetchNewFrame();
  9153. }
  9154. var currentTime = Tools.Now;
  9155. this._current = currentTime - this._startMonitoringTime;
  9156. if (newFrame) {
  9157. this._fetchResult();
  9158. }
  9159. };
  9160. PerfCounter.prototype._fetchResult = function () {
  9161. this._totalAccumulated += this._current;
  9162. this._lastSecAccumulated += this._current;
  9163. // Min/Max update
  9164. this._min = Math.min(this._min, this._current);
  9165. this._max = Math.max(this._max, this._current);
  9166. this._average = this._totalAccumulated / this._totalValueCount;
  9167. // Reset last sec?
  9168. var now = Tools.Now;
  9169. if ((now - this._lastSecTime) > 1000) {
  9170. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9171. this._lastSecTime = now;
  9172. this._lastSecAccumulated = 0;
  9173. this._lastSecValueCount = 0;
  9174. }
  9175. };
  9176. PerfCounter.Enabled = true;
  9177. return PerfCounter;
  9178. }());
  9179. BABYLON.PerfCounter = PerfCounter;
  9180. /**
  9181. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9182. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9183. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9184. * @param name The name of the class, case should be preserved
  9185. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9186. */
  9187. function className(name, module) {
  9188. return function (target) {
  9189. target["__bjsclassName__"] = name;
  9190. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9191. };
  9192. }
  9193. BABYLON.className = className;
  9194. /**
  9195. * An implementation of a loop for asynchronous functions.
  9196. */
  9197. var AsyncLoop = /** @class */ (function () {
  9198. /**
  9199. * Constroctor.
  9200. * @param iterations the number of iterations.
  9201. * @param _fn the function to run each iteration
  9202. * @param _successCallback the callback that will be called upon succesful execution
  9203. * @param offset starting offset.
  9204. */
  9205. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9206. if (offset === void 0) { offset = 0; }
  9207. this.iterations = iterations;
  9208. this._fn = _fn;
  9209. this._successCallback = _successCallback;
  9210. this.index = offset - 1;
  9211. this._done = false;
  9212. }
  9213. /**
  9214. * Execute the next iteration. Must be called after the last iteration was finished.
  9215. */
  9216. AsyncLoop.prototype.executeNext = function () {
  9217. if (!this._done) {
  9218. if (this.index + 1 < this.iterations) {
  9219. ++this.index;
  9220. this._fn(this);
  9221. }
  9222. else {
  9223. this.breakLoop();
  9224. }
  9225. }
  9226. };
  9227. /**
  9228. * Break the loop and run the success callback.
  9229. */
  9230. AsyncLoop.prototype.breakLoop = function () {
  9231. this._done = true;
  9232. this._successCallback();
  9233. };
  9234. /**
  9235. * Helper function
  9236. */
  9237. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9238. if (offset === void 0) { offset = 0; }
  9239. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9240. loop.executeNext();
  9241. return loop;
  9242. };
  9243. /**
  9244. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9245. * @param iterations total number of iterations
  9246. * @param syncedIterations number of synchronous iterations in each async iteration.
  9247. * @param fn the function to call each iteration.
  9248. * @param callback a success call back that will be called when iterating stops.
  9249. * @param breakFunction a break condition (optional)
  9250. * @param timeout timeout settings for the setTimeout function. default - 0.
  9251. * @constructor
  9252. */
  9253. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9254. if (timeout === void 0) { timeout = 0; }
  9255. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9256. if (breakFunction && breakFunction())
  9257. loop.breakLoop();
  9258. else {
  9259. setTimeout(function () {
  9260. for (var i = 0; i < syncedIterations; ++i) {
  9261. var iteration = (loop.index * syncedIterations) + i;
  9262. if (iteration >= iterations)
  9263. break;
  9264. fn(iteration);
  9265. if (breakFunction && breakFunction()) {
  9266. loop.breakLoop();
  9267. break;
  9268. }
  9269. }
  9270. loop.executeNext();
  9271. }, timeout);
  9272. }
  9273. }, callback);
  9274. };
  9275. return AsyncLoop;
  9276. }());
  9277. BABYLON.AsyncLoop = AsyncLoop;
  9278. })(BABYLON || (BABYLON = {}));
  9279. //# sourceMappingURL=babylon.tools.js.map
  9280. var BABYLON;
  9281. (function (BABYLON) {
  9282. var PromiseStates;
  9283. (function (PromiseStates) {
  9284. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9285. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9286. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9287. })(PromiseStates || (PromiseStates = {}));
  9288. var FulFillmentAgregator = /** @class */ (function () {
  9289. function FulFillmentAgregator() {
  9290. this.count = 0;
  9291. this.target = 0;
  9292. this.results = [];
  9293. }
  9294. return FulFillmentAgregator;
  9295. }());
  9296. var InternalPromise = /** @class */ (function () {
  9297. function InternalPromise(resolver) {
  9298. var _this = this;
  9299. this._state = PromiseStates.Pending;
  9300. this._children = new Array();
  9301. this._rejectWasConsumed = false;
  9302. if (!resolver) {
  9303. return;
  9304. }
  9305. try {
  9306. resolver(function (value) {
  9307. _this._resolve(value);
  9308. }, function (reason) {
  9309. _this._reject(reason);
  9310. });
  9311. }
  9312. catch (e) {
  9313. this._reject(e);
  9314. }
  9315. }
  9316. InternalPromise.prototype.catch = function (onRejected) {
  9317. return this.then(undefined, onRejected);
  9318. };
  9319. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9320. var _this = this;
  9321. var newPromise = new InternalPromise();
  9322. newPromise._onFulfilled = onFulfilled;
  9323. newPromise._onRejected = onRejected;
  9324. // Composition
  9325. this._children.push(newPromise);
  9326. if (this._state !== PromiseStates.Pending) {
  9327. BABYLON.Tools.SetImmediate(function () {
  9328. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9329. var returnedValue = newPromise._resolve(_this._result);
  9330. if (returnedValue !== undefined && returnedValue !== null) {
  9331. if (returnedValue._state !== undefined) {
  9332. var returnedPromise = returnedValue;
  9333. newPromise._children.push(returnedPromise);
  9334. newPromise = returnedPromise;
  9335. }
  9336. else {
  9337. newPromise._result = returnedValue;
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. newPromise._reject(_this._reason);
  9343. }
  9344. });
  9345. }
  9346. return newPromise;
  9347. };
  9348. InternalPromise.prototype._moveChildren = function (children) {
  9349. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9350. if (this._state === PromiseStates.Fulfilled) {
  9351. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9352. var child = _b[_i];
  9353. child._resolve(this._result);
  9354. }
  9355. }
  9356. else if (this._state === PromiseStates.Rejected) {
  9357. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9358. var child = _d[_c];
  9359. child._reject(this._reason);
  9360. }
  9361. }
  9362. var _a;
  9363. };
  9364. InternalPromise.prototype._resolve = function (value) {
  9365. try {
  9366. this._state = PromiseStates.Fulfilled;
  9367. this._result = value;
  9368. var returnedValue = null;
  9369. if (this._onFulfilled) {
  9370. returnedValue = this._onFulfilled(value);
  9371. }
  9372. if (returnedValue !== undefined && returnedValue !== null) {
  9373. if (returnedValue._state !== undefined) {
  9374. // Transmit children
  9375. var returnedPromise = returnedValue;
  9376. returnedPromise._moveChildren(this._children);
  9377. }
  9378. else {
  9379. value = returnedValue;
  9380. }
  9381. }
  9382. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9383. var child = _a[_i];
  9384. child._resolve(value);
  9385. }
  9386. this._children.length = 0;
  9387. delete this._onFulfilled;
  9388. delete this._onRejected;
  9389. return returnedValue;
  9390. }
  9391. catch (e) {
  9392. this._reject(e, true);
  9393. }
  9394. return null;
  9395. };
  9396. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9397. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9398. this._state = PromiseStates.Rejected;
  9399. this._reason = reason;
  9400. if (this._onRejected && !onLocalThrow) {
  9401. try {
  9402. this._onRejected(reason);
  9403. this._rejectWasConsumed = true;
  9404. }
  9405. catch (e) {
  9406. reason = e;
  9407. }
  9408. }
  9409. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9410. var child = _a[_i];
  9411. if (this._rejectWasConsumed) {
  9412. child._resolve(null);
  9413. }
  9414. else {
  9415. child._reject(reason);
  9416. }
  9417. }
  9418. this._children.length = 0;
  9419. delete this._onFulfilled;
  9420. delete this._onRejected;
  9421. };
  9422. InternalPromise.resolve = function (value) {
  9423. var newPromise = new InternalPromise();
  9424. newPromise._resolve(value);
  9425. return newPromise;
  9426. };
  9427. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9428. promise.then(function (value) {
  9429. agregator.results[index] = value;
  9430. agregator.count++;
  9431. if (agregator.count === agregator.target) {
  9432. agregator.rootPromise._resolve(agregator.results);
  9433. }
  9434. return null;
  9435. }, function (reason) {
  9436. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9437. agregator.rootPromise._reject(reason);
  9438. }
  9439. });
  9440. };
  9441. InternalPromise.all = function (promises) {
  9442. var newPromise = new InternalPromise();
  9443. var agregator = new FulFillmentAgregator();
  9444. agregator.target = promises.length;
  9445. agregator.rootPromise = newPromise;
  9446. if (promises.length) {
  9447. for (var index = 0; index < promises.length; index++) {
  9448. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9449. }
  9450. }
  9451. else {
  9452. newPromise._resolve([]);
  9453. }
  9454. return newPromise;
  9455. };
  9456. return InternalPromise;
  9457. }());
  9458. /**
  9459. * Helper class that provides a small promise polyfill
  9460. */
  9461. var PromisePolyfill = /** @class */ (function () {
  9462. function PromisePolyfill() {
  9463. }
  9464. /**
  9465. * Static function used to check if the polyfill is required
  9466. * If this is the case then the function will inject the polyfill to window.Promise
  9467. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9468. */
  9469. PromisePolyfill.Apply = function (force) {
  9470. if (force === void 0) { force = false; }
  9471. if (force || typeof Promise === 'undefined') {
  9472. var root = window;
  9473. root.Promise = InternalPromise;
  9474. }
  9475. };
  9476. return PromisePolyfill;
  9477. }());
  9478. BABYLON.PromisePolyfill = PromisePolyfill;
  9479. })(BABYLON || (BABYLON = {}));
  9480. //# sourceMappingURL=babylon.promise.js.map
  9481. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9482. var BABYLON;
  9483. (function (BABYLON) {
  9484. /**
  9485. * Helper class to push actions to a pool of workers.
  9486. */
  9487. var WorkerPool = /** @class */ (function () {
  9488. /**
  9489. * Constructor
  9490. * @param workers Array of workers to use for actions
  9491. */
  9492. function WorkerPool(workers) {
  9493. this._pendingActions = new Array();
  9494. this._workerInfos = workers.map(function (worker) { return ({
  9495. worker: worker,
  9496. active: false
  9497. }); });
  9498. }
  9499. /**
  9500. * Terminates all workers and clears any pending actions.
  9501. */
  9502. WorkerPool.prototype.dispose = function () {
  9503. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9504. var workerInfo = _a[_i];
  9505. workerInfo.worker.terminate();
  9506. }
  9507. delete this._workerInfos;
  9508. delete this._pendingActions;
  9509. };
  9510. /**
  9511. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9512. * pended until a worker has completed its action.
  9513. * @param action The action to perform. Call onComplete when the action is complete.
  9514. */
  9515. WorkerPool.prototype.push = function (action) {
  9516. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9517. var workerInfo = _a[_i];
  9518. if (!workerInfo.active) {
  9519. this._execute(workerInfo, action);
  9520. return;
  9521. }
  9522. }
  9523. this._pendingActions.push(action);
  9524. };
  9525. WorkerPool.prototype._execute = function (workerInfo, action) {
  9526. var _this = this;
  9527. workerInfo.active = true;
  9528. action(workerInfo.worker, function () {
  9529. workerInfo.active = false;
  9530. var nextAction = _this._pendingActions.shift();
  9531. if (nextAction) {
  9532. _this._execute(workerInfo, nextAction);
  9533. }
  9534. });
  9535. };
  9536. return WorkerPool;
  9537. }());
  9538. BABYLON.WorkerPool = WorkerPool;
  9539. })(BABYLON || (BABYLON = {}));
  9540. //# sourceMappingURL=babylon.workerPool.js.map
  9541. var BABYLON;
  9542. (function (BABYLON) {
  9543. var _AlphaState = /** @class */ (function () {
  9544. /**
  9545. * Initializes the state.
  9546. */
  9547. function _AlphaState() {
  9548. this._isAlphaBlendDirty = false;
  9549. this._isBlendFunctionParametersDirty = false;
  9550. this._isBlendEquationParametersDirty = false;
  9551. this._isBlendConstantsDirty = false;
  9552. this._alphaBlend = false;
  9553. this._blendFunctionParameters = new Array(4);
  9554. this._blendEquationParameters = new Array(2);
  9555. this._blendConstants = new Array(4);
  9556. this.reset();
  9557. }
  9558. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9559. get: function () {
  9560. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9566. get: function () {
  9567. return this._alphaBlend;
  9568. },
  9569. set: function (value) {
  9570. if (this._alphaBlend === value) {
  9571. return;
  9572. }
  9573. this._alphaBlend = value;
  9574. this._isAlphaBlendDirty = true;
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9580. if (this._blendConstants[0] === r &&
  9581. this._blendConstants[1] === g &&
  9582. this._blendConstants[2] === b &&
  9583. this._blendConstants[3] === a) {
  9584. return;
  9585. }
  9586. this._blendConstants[0] = r;
  9587. this._blendConstants[1] = g;
  9588. this._blendConstants[2] = b;
  9589. this._blendConstants[3] = a;
  9590. this._isBlendConstantsDirty = true;
  9591. };
  9592. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9593. if (this._blendFunctionParameters[0] === value0 &&
  9594. this._blendFunctionParameters[1] === value1 &&
  9595. this._blendFunctionParameters[2] === value2 &&
  9596. this._blendFunctionParameters[3] === value3) {
  9597. return;
  9598. }
  9599. this._blendFunctionParameters[0] = value0;
  9600. this._blendFunctionParameters[1] = value1;
  9601. this._blendFunctionParameters[2] = value2;
  9602. this._blendFunctionParameters[3] = value3;
  9603. this._isBlendFunctionParametersDirty = true;
  9604. };
  9605. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9606. if (this._blendEquationParameters[0] === rgb &&
  9607. this._blendEquationParameters[1] === alpha) {
  9608. return;
  9609. }
  9610. this._blendEquationParameters[0] = rgb;
  9611. this._blendEquationParameters[1] = alpha;
  9612. this._isBlendEquationParametersDirty = true;
  9613. };
  9614. _AlphaState.prototype.reset = function () {
  9615. this._alphaBlend = false;
  9616. this._blendFunctionParameters[0] = null;
  9617. this._blendFunctionParameters[1] = null;
  9618. this._blendFunctionParameters[2] = null;
  9619. this._blendFunctionParameters[3] = null;
  9620. this._blendEquationParameters[0] = null;
  9621. this._blendEquationParameters[1] = null;
  9622. this._blendConstants[0] = null;
  9623. this._blendConstants[1] = null;
  9624. this._blendConstants[2] = null;
  9625. this._blendConstants[3] = null;
  9626. this._isAlphaBlendDirty = true;
  9627. this._isBlendFunctionParametersDirty = false;
  9628. this._isBlendEquationParametersDirty = false;
  9629. this._isBlendConstantsDirty = false;
  9630. };
  9631. _AlphaState.prototype.apply = function (gl) {
  9632. if (!this.isDirty) {
  9633. return;
  9634. }
  9635. // Alpha blend
  9636. if (this._isAlphaBlendDirty) {
  9637. if (this._alphaBlend) {
  9638. gl.enable(gl.BLEND);
  9639. }
  9640. else {
  9641. gl.disable(gl.BLEND);
  9642. }
  9643. this._isAlphaBlendDirty = false;
  9644. }
  9645. // Alpha function
  9646. if (this._isBlendFunctionParametersDirty) {
  9647. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9648. this._isBlendFunctionParametersDirty = false;
  9649. }
  9650. // Alpha equation
  9651. if (this._isBlendEquationParametersDirty) {
  9652. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9653. this._isBlendEquationParametersDirty = false;
  9654. }
  9655. // Constants
  9656. if (this._isBlendConstantsDirty) {
  9657. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9658. this._isBlendConstantsDirty = false;
  9659. }
  9660. };
  9661. return _AlphaState;
  9662. }());
  9663. BABYLON._AlphaState = _AlphaState;
  9664. })(BABYLON || (BABYLON = {}));
  9665. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9666. var BABYLON;
  9667. (function (BABYLON) {
  9668. var _DepthCullingState = /** @class */ (function () {
  9669. /**
  9670. * Initializes the state.
  9671. */
  9672. function _DepthCullingState() {
  9673. this._isDepthTestDirty = false;
  9674. this._isDepthMaskDirty = false;
  9675. this._isDepthFuncDirty = false;
  9676. this._isCullFaceDirty = false;
  9677. this._isCullDirty = false;
  9678. this._isZOffsetDirty = false;
  9679. this._isFrontFaceDirty = false;
  9680. this.reset();
  9681. }
  9682. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9683. get: function () {
  9684. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9690. get: function () {
  9691. return this._zOffset;
  9692. },
  9693. set: function (value) {
  9694. if (this._zOffset === value) {
  9695. return;
  9696. }
  9697. this._zOffset = value;
  9698. this._isZOffsetDirty = true;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9704. get: function () {
  9705. return this._cullFace;
  9706. },
  9707. set: function (value) {
  9708. if (this._cullFace === value) {
  9709. return;
  9710. }
  9711. this._cullFace = value;
  9712. this._isCullFaceDirty = true;
  9713. },
  9714. enumerable: true,
  9715. configurable: true
  9716. });
  9717. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9718. get: function () {
  9719. return this._cull;
  9720. },
  9721. set: function (value) {
  9722. if (this._cull === value) {
  9723. return;
  9724. }
  9725. this._cull = value;
  9726. this._isCullDirty = true;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9732. get: function () {
  9733. return this._depthFunc;
  9734. },
  9735. set: function (value) {
  9736. if (this._depthFunc === value) {
  9737. return;
  9738. }
  9739. this._depthFunc = value;
  9740. this._isDepthFuncDirty = true;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9746. get: function () {
  9747. return this._depthMask;
  9748. },
  9749. set: function (value) {
  9750. if (this._depthMask === value) {
  9751. return;
  9752. }
  9753. this._depthMask = value;
  9754. this._isDepthMaskDirty = true;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9760. get: function () {
  9761. return this._depthTest;
  9762. },
  9763. set: function (value) {
  9764. if (this._depthTest === value) {
  9765. return;
  9766. }
  9767. this._depthTest = value;
  9768. this._isDepthTestDirty = true;
  9769. },
  9770. enumerable: true,
  9771. configurable: true
  9772. });
  9773. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9774. get: function () {
  9775. return this._frontFace;
  9776. },
  9777. set: function (value) {
  9778. if (this._frontFace === value) {
  9779. return;
  9780. }
  9781. this._frontFace = value;
  9782. this._isFrontFaceDirty = true;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. _DepthCullingState.prototype.reset = function () {
  9788. this._depthMask = true;
  9789. this._depthTest = true;
  9790. this._depthFunc = null;
  9791. this._cullFace = null;
  9792. this._cull = null;
  9793. this._zOffset = 0;
  9794. this._frontFace = null;
  9795. this._isDepthTestDirty = true;
  9796. this._isDepthMaskDirty = true;
  9797. this._isDepthFuncDirty = false;
  9798. this._isCullFaceDirty = false;
  9799. this._isCullDirty = false;
  9800. this._isZOffsetDirty = false;
  9801. this._isFrontFaceDirty = false;
  9802. };
  9803. _DepthCullingState.prototype.apply = function (gl) {
  9804. if (!this.isDirty) {
  9805. return;
  9806. }
  9807. // Cull
  9808. if (this._isCullDirty) {
  9809. if (this.cull) {
  9810. gl.enable(gl.CULL_FACE);
  9811. }
  9812. else {
  9813. gl.disable(gl.CULL_FACE);
  9814. }
  9815. this._isCullDirty = false;
  9816. }
  9817. // Cull face
  9818. if (this._isCullFaceDirty) {
  9819. gl.cullFace(this.cullFace);
  9820. this._isCullFaceDirty = false;
  9821. }
  9822. // Depth mask
  9823. if (this._isDepthMaskDirty) {
  9824. gl.depthMask(this.depthMask);
  9825. this._isDepthMaskDirty = false;
  9826. }
  9827. // Depth test
  9828. if (this._isDepthTestDirty) {
  9829. if (this.depthTest) {
  9830. gl.enable(gl.DEPTH_TEST);
  9831. }
  9832. else {
  9833. gl.disable(gl.DEPTH_TEST);
  9834. }
  9835. this._isDepthTestDirty = false;
  9836. }
  9837. // Depth func
  9838. if (this._isDepthFuncDirty) {
  9839. gl.depthFunc(this.depthFunc);
  9840. this._isDepthFuncDirty = false;
  9841. }
  9842. // zOffset
  9843. if (this._isZOffsetDirty) {
  9844. if (this.zOffset) {
  9845. gl.enable(gl.POLYGON_OFFSET_FILL);
  9846. gl.polygonOffset(this.zOffset, 0);
  9847. }
  9848. else {
  9849. gl.disable(gl.POLYGON_OFFSET_FILL);
  9850. }
  9851. this._isZOffsetDirty = false;
  9852. }
  9853. // Front face
  9854. if (this._isFrontFaceDirty) {
  9855. gl.frontFace(this.frontFace);
  9856. this._isFrontFaceDirty = false;
  9857. }
  9858. };
  9859. return _DepthCullingState;
  9860. }());
  9861. BABYLON._DepthCullingState = _DepthCullingState;
  9862. })(BABYLON || (BABYLON = {}));
  9863. //# sourceMappingURL=babylon.depthCullingState.js.map
  9864. var BABYLON;
  9865. (function (BABYLON) {
  9866. var _StencilState = /** @class */ (function () {
  9867. function _StencilState() {
  9868. this._isStencilTestDirty = false;
  9869. this._isStencilMaskDirty = false;
  9870. this._isStencilFuncDirty = false;
  9871. this._isStencilOpDirty = false;
  9872. this.reset();
  9873. }
  9874. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9875. get: function () {
  9876. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9882. get: function () {
  9883. return this._stencilFunc;
  9884. },
  9885. set: function (value) {
  9886. if (this._stencilFunc === value) {
  9887. return;
  9888. }
  9889. this._stencilFunc = value;
  9890. this._isStencilFuncDirty = true;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9896. get: function () {
  9897. return this._stencilFuncRef;
  9898. },
  9899. set: function (value) {
  9900. if (this._stencilFuncRef === value) {
  9901. return;
  9902. }
  9903. this._stencilFuncRef = value;
  9904. this._isStencilFuncDirty = true;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9910. get: function () {
  9911. return this._stencilFuncMask;
  9912. },
  9913. set: function (value) {
  9914. if (this._stencilFuncMask === value) {
  9915. return;
  9916. }
  9917. this._stencilFuncMask = value;
  9918. this._isStencilFuncDirty = true;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9924. get: function () {
  9925. return this._stencilOpStencilFail;
  9926. },
  9927. set: function (value) {
  9928. if (this._stencilOpStencilFail === value) {
  9929. return;
  9930. }
  9931. this._stencilOpStencilFail = value;
  9932. this._isStencilOpDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9938. get: function () {
  9939. return this._stencilOpDepthFail;
  9940. },
  9941. set: function (value) {
  9942. if (this._stencilOpDepthFail === value) {
  9943. return;
  9944. }
  9945. this._stencilOpDepthFail = value;
  9946. this._isStencilOpDirty = true;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9952. get: function () {
  9953. return this._stencilOpStencilDepthPass;
  9954. },
  9955. set: function (value) {
  9956. if (this._stencilOpStencilDepthPass === value) {
  9957. return;
  9958. }
  9959. this._stencilOpStencilDepthPass = value;
  9960. this._isStencilOpDirty = true;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9966. get: function () {
  9967. return this._stencilMask;
  9968. },
  9969. set: function (value) {
  9970. if (this._stencilMask === value) {
  9971. return;
  9972. }
  9973. this._stencilMask = value;
  9974. this._isStencilMaskDirty = true;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9980. get: function () {
  9981. return this._stencilTest;
  9982. },
  9983. set: function (value) {
  9984. if (this._stencilTest === value) {
  9985. return;
  9986. }
  9987. this._stencilTest = value;
  9988. this._isStencilTestDirty = true;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. _StencilState.prototype.reset = function () {
  9994. this._stencilTest = false;
  9995. this._stencilMask = 0xFF;
  9996. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9997. this._stencilFuncRef = 1;
  9998. this._stencilFuncMask = 0xFF;
  9999. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10000. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10001. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10002. this._isStencilTestDirty = true;
  10003. this._isStencilMaskDirty = true;
  10004. this._isStencilFuncDirty = true;
  10005. this._isStencilOpDirty = true;
  10006. };
  10007. _StencilState.prototype.apply = function (gl) {
  10008. if (!this.isDirty) {
  10009. return;
  10010. }
  10011. // Stencil test
  10012. if (this._isStencilTestDirty) {
  10013. if (this.stencilTest) {
  10014. gl.enable(gl.STENCIL_TEST);
  10015. }
  10016. else {
  10017. gl.disable(gl.STENCIL_TEST);
  10018. }
  10019. this._isStencilTestDirty = false;
  10020. }
  10021. // Stencil mask
  10022. if (this._isStencilMaskDirty) {
  10023. gl.stencilMask(this.stencilMask);
  10024. this._isStencilMaskDirty = false;
  10025. }
  10026. // Stencil func
  10027. if (this._isStencilFuncDirty) {
  10028. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10029. this._isStencilFuncDirty = false;
  10030. }
  10031. // Stencil op
  10032. if (this._isStencilOpDirty) {
  10033. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10034. this._isStencilOpDirty = false;
  10035. }
  10036. };
  10037. return _StencilState;
  10038. }());
  10039. BABYLON._StencilState = _StencilState;
  10040. })(BABYLON || (BABYLON = {}));
  10041. //# sourceMappingURL=babylon.stencilState.js.map
  10042. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10043. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10044. s = arguments[i];
  10045. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10046. t[p] = s[p];
  10047. }
  10048. return t;
  10049. };
  10050. var BABYLON;
  10051. (function (BABYLON) {
  10052. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10053. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10054. };
  10055. var compileRawShader = function (gl, source, type) {
  10056. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10057. gl.shaderSource(shader, source);
  10058. gl.compileShader(shader);
  10059. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10060. var log = gl.getShaderInfoLog(shader);
  10061. if (log) {
  10062. throw new Error(log);
  10063. }
  10064. }
  10065. if (!shader) {
  10066. throw new Error("Something went wrong while compile the shader.");
  10067. }
  10068. return shader;
  10069. };
  10070. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10071. var magFilter = gl.NEAREST;
  10072. var minFilter = gl.NEAREST;
  10073. switch (samplingMode) {
  10074. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10075. magFilter = gl.LINEAR;
  10076. if (generateMipMaps) {
  10077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10078. }
  10079. else {
  10080. minFilter = gl.LINEAR;
  10081. }
  10082. break;
  10083. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10084. magFilter = gl.LINEAR;
  10085. if (generateMipMaps) {
  10086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10087. }
  10088. else {
  10089. minFilter = gl.LINEAR;
  10090. }
  10091. break;
  10092. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10093. magFilter = gl.NEAREST;
  10094. if (generateMipMaps) {
  10095. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10096. }
  10097. else {
  10098. minFilter = gl.NEAREST;
  10099. }
  10100. break;
  10101. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10102. magFilter = gl.NEAREST;
  10103. if (generateMipMaps) {
  10104. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10105. }
  10106. else {
  10107. minFilter = gl.NEAREST;
  10108. }
  10109. break;
  10110. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10111. magFilter = gl.NEAREST;
  10112. if (generateMipMaps) {
  10113. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10114. }
  10115. else {
  10116. minFilter = gl.LINEAR;
  10117. }
  10118. break;
  10119. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10120. magFilter = gl.NEAREST;
  10121. if (generateMipMaps) {
  10122. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10123. }
  10124. else {
  10125. minFilter = gl.LINEAR;
  10126. }
  10127. break;
  10128. case BABYLON.Texture.NEAREST_LINEAR:
  10129. magFilter = gl.NEAREST;
  10130. minFilter = gl.LINEAR;
  10131. break;
  10132. case BABYLON.Texture.NEAREST_NEAREST:
  10133. magFilter = gl.NEAREST;
  10134. minFilter = gl.NEAREST;
  10135. break;
  10136. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10137. magFilter = gl.LINEAR;
  10138. if (generateMipMaps) {
  10139. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10140. }
  10141. else {
  10142. minFilter = gl.NEAREST;
  10143. }
  10144. break;
  10145. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10146. magFilter = gl.LINEAR;
  10147. if (generateMipMaps) {
  10148. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10149. }
  10150. else {
  10151. minFilter = gl.NEAREST;
  10152. }
  10153. break;
  10154. case BABYLON.Texture.LINEAR_LINEAR:
  10155. magFilter = gl.LINEAR;
  10156. minFilter = gl.LINEAR;
  10157. break;
  10158. case BABYLON.Texture.LINEAR_NEAREST:
  10159. magFilter = gl.LINEAR;
  10160. minFilter = gl.NEAREST;
  10161. break;
  10162. }
  10163. return {
  10164. min: minFilter,
  10165. mag: magFilter
  10166. };
  10167. };
  10168. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10169. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10170. var img;
  10171. var onload = function () {
  10172. loadedImages[index] = img;
  10173. loadedImages._internalCount++;
  10174. if (scene) {
  10175. scene._removePendingData(img);
  10176. }
  10177. if (loadedImages._internalCount === 6) {
  10178. onfinish(loadedImages);
  10179. }
  10180. };
  10181. var onerror = function (message, exception) {
  10182. if (scene) {
  10183. scene._removePendingData(img);
  10184. }
  10185. if (onErrorCallBack) {
  10186. onErrorCallBack(message, exception);
  10187. }
  10188. };
  10189. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10190. if (scene) {
  10191. scene._addPendingData(img);
  10192. }
  10193. };
  10194. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10195. if (onError === void 0) { onError = null; }
  10196. var loadedImages = [];
  10197. loadedImages._internalCount = 0;
  10198. for (var index = 0; index < 6; index++) {
  10199. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10200. }
  10201. };
  10202. var BufferPointer = /** @class */ (function () {
  10203. function BufferPointer() {
  10204. }
  10205. return BufferPointer;
  10206. }());
  10207. var InstancingAttributeInfo = /** @class */ (function () {
  10208. function InstancingAttributeInfo() {
  10209. }
  10210. return InstancingAttributeInfo;
  10211. }());
  10212. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10213. /**
  10214. * Define options used to create a render target texture
  10215. */
  10216. var RenderTargetCreationOptions = /** @class */ (function () {
  10217. function RenderTargetCreationOptions() {
  10218. }
  10219. return RenderTargetCreationOptions;
  10220. }());
  10221. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10222. /**
  10223. * Define options used to create a depth texture
  10224. */
  10225. var DepthTextureCreationOptions = /** @class */ (function () {
  10226. function DepthTextureCreationOptions() {
  10227. }
  10228. return DepthTextureCreationOptions;
  10229. }());
  10230. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10231. /**
  10232. * Regroup several parameters relative to the browser in use
  10233. */
  10234. var EngineCapabilities = /** @class */ (function () {
  10235. function EngineCapabilities() {
  10236. }
  10237. return EngineCapabilities;
  10238. }());
  10239. BABYLON.EngineCapabilities = EngineCapabilities;
  10240. /**
  10241. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10242. */
  10243. var Engine = /** @class */ (function () {
  10244. /**
  10245. * @constructor
  10246. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10247. * @param antialias defines enable antialiasing (default: false)
  10248. * @param options defines further options to be sent to the getContext() function
  10249. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10250. */
  10251. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10252. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10253. var _this = this;
  10254. // Public members
  10255. this.forcePOTTextures = false;
  10256. this.isFullscreen = false;
  10257. this.isPointerLock = false;
  10258. this.cullBackFaces = true;
  10259. this.renderEvenInBackground = true;
  10260. this.preventCacheWipeBetweenFrames = false;
  10261. // To enable/disable IDB support and avoid XHR on .manifest
  10262. this.enableOfflineSupport = false;
  10263. this.scenes = new Array();
  10264. this.postProcesses = new Array();
  10265. // Observables
  10266. /**
  10267. * Observable event triggered each time the rendering canvas is resized
  10268. */
  10269. this.onResizeObservable = new BABYLON.Observable();
  10270. /**
  10271. * Observable event triggered each time the canvas loses focus
  10272. */
  10273. this.onCanvasBlurObservable = new BABYLON.Observable();
  10274. /**
  10275. * Observable event triggered each time the canvas gains focus
  10276. */
  10277. this.onCanvasFocusObservable = new BABYLON.Observable();
  10278. /**
  10279. * Observable event triggered each time the canvas receives pointerout event
  10280. */
  10281. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10282. /**
  10283. * Observable event triggered before each texture is initialized
  10284. */
  10285. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10286. //WebVR
  10287. this._vrDisplay = undefined;
  10288. this._vrSupported = false;
  10289. this._vrExclusivePointerMode = false;
  10290. // Uniform buffers list
  10291. this.disableUniformBuffers = false;
  10292. this._uniformBuffers = new Array();
  10293. // Observables
  10294. /**
  10295. * Observable raised when the engine begins a new frame
  10296. */
  10297. this.onBeginFrameObservable = new BABYLON.Observable();
  10298. /**
  10299. * Observable raised when the engine ends the current frame
  10300. */
  10301. this.onEndFrameObservable = new BABYLON.Observable();
  10302. /**
  10303. * Observable raised when the engine is about to compile a shader
  10304. */
  10305. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10306. /**
  10307. * Observable raised when the engine has jsut compiled a shader
  10308. */
  10309. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10310. this._windowIsBackground = false;
  10311. this._webGLVersion = 1.0;
  10312. this._badOS = false;
  10313. this._badDesktopOS = false;
  10314. /**
  10315. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10316. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10317. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10318. */
  10319. this.disableTextureBindingOptimization = false;
  10320. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10321. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10322. this.onVRRequestPresentStart = new BABYLON.Observable();
  10323. this._colorWrite = true;
  10324. this._drawCalls = new BABYLON.PerfCounter();
  10325. this._textureCollisions = new BABYLON.PerfCounter();
  10326. this._renderingQueueLaunched = false;
  10327. this._activeRenderLoops = new Array();
  10328. // Deterministic lockstepMaxSteps
  10329. this._deterministicLockstep = false;
  10330. this._lockstepMaxSteps = 4;
  10331. // Lost context
  10332. this.onContextLostObservable = new BABYLON.Observable();
  10333. this.onContextRestoredObservable = new BABYLON.Observable();
  10334. this._contextWasLost = false;
  10335. this._doNotHandleContextLost = false;
  10336. // FPS
  10337. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10338. this._fps = 60;
  10339. this._deltaTime = 0;
  10340. /**
  10341. * Turn this value on if you want to pause FPS computation when in background
  10342. */
  10343. this.disablePerformanceMonitorInBackground = false;
  10344. // States
  10345. this._depthCullingState = new BABYLON._DepthCullingState();
  10346. this._stencilState = new BABYLON._StencilState();
  10347. this._alphaState = new BABYLON._AlphaState();
  10348. this._alphaMode = Engine.ALPHA_DISABLE;
  10349. // Cache
  10350. this._internalTexturesCache = new Array();
  10351. this._activeChannel = 0;
  10352. this._currentTextureChannel = -1;
  10353. this._boundTexturesCache = {};
  10354. this._compiledEffects = {};
  10355. this._vertexAttribArraysEnabled = [];
  10356. this._uintIndicesCurrentlySet = false;
  10357. this._currentBoundBuffer = new Array();
  10358. this._currentBufferPointers = new Array();
  10359. this._currentInstanceLocations = new Array();
  10360. this._currentInstanceBuffers = new Array();
  10361. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10362. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10363. this._vaoRecordInProgress = false;
  10364. this._mustWipeVertexAttributes = false;
  10365. this._nextFreeTextureSlots = new Array();
  10366. this._maxSimultaneousTextures = 0;
  10367. this._activeRequests = new Array();
  10368. // Hardware supported Compressed Textures
  10369. this._texturesSupported = new Array();
  10370. this._onVRFullScreenTriggered = function () {
  10371. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10372. //get the old size before we change
  10373. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10374. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10375. //get the width and height, change the render size
  10376. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10377. _this.setHardwareScalingLevel(1);
  10378. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10379. }
  10380. else {
  10381. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10382. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10383. }
  10384. };
  10385. this._boundUniforms = {};
  10386. // Register promises
  10387. BABYLON.PromisePolyfill.Apply();
  10388. var canvas = null;
  10389. Engine.Instances.push(this);
  10390. if (!canvasOrContext) {
  10391. return;
  10392. }
  10393. options = options || {};
  10394. if (canvasOrContext.getContext) {
  10395. canvas = canvasOrContext;
  10396. this._renderingCanvas = canvas;
  10397. if (antialias != null) {
  10398. options.antialias = antialias;
  10399. }
  10400. if (options.deterministicLockstep === undefined) {
  10401. options.deterministicLockstep = false;
  10402. }
  10403. if (options.lockstepMaxSteps === undefined) {
  10404. options.lockstepMaxSteps = 4;
  10405. }
  10406. if (options.preserveDrawingBuffer === undefined) {
  10407. options.preserveDrawingBuffer = false;
  10408. }
  10409. if (options.audioEngine === undefined) {
  10410. options.audioEngine = true;
  10411. }
  10412. if (options.stencil === undefined) {
  10413. options.stencil = true;
  10414. }
  10415. this._deterministicLockstep = options.deterministicLockstep;
  10416. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10417. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10418. // Exceptions
  10419. if (navigator && navigator.userAgent) {
  10420. var ua = navigator.userAgent;
  10421. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10422. var exception = _a[_i];
  10423. var key = exception.key;
  10424. var targets = exception.targets;
  10425. if (ua.indexOf(key) > -1) {
  10426. if (exception.capture && exception.captureConstraint) {
  10427. var capture = exception.capture;
  10428. var constraint = exception.captureConstraint;
  10429. var regex = new RegExp(capture);
  10430. var matches = regex.exec(ua);
  10431. if (matches && matches.length > 0) {
  10432. var capturedValue = parseInt(matches[matches.length - 1]);
  10433. if (capturedValue >= constraint) {
  10434. continue;
  10435. }
  10436. }
  10437. }
  10438. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10439. var target = targets_1[_b];
  10440. switch (target) {
  10441. case "uniformBuffer":
  10442. this.disableUniformBuffers = true;
  10443. break;
  10444. case "textureBindingOptimization":
  10445. this.disableTextureBindingOptimization = true;
  10446. break;
  10447. }
  10448. }
  10449. break;
  10450. }
  10451. }
  10452. }
  10453. // GL
  10454. if (!options.disableWebGL2Support) {
  10455. try {
  10456. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10457. if (this._gl) {
  10458. this._webGLVersion = 2.0;
  10459. }
  10460. }
  10461. catch (e) {
  10462. // Do nothing
  10463. }
  10464. }
  10465. if (!this._gl) {
  10466. if (!canvas) {
  10467. throw new Error("The provided canvas is null or undefined.");
  10468. }
  10469. try {
  10470. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10471. }
  10472. catch (e) {
  10473. throw new Error("WebGL not supported");
  10474. }
  10475. }
  10476. if (!this._gl) {
  10477. throw new Error("WebGL not supported");
  10478. }
  10479. this._onCanvasFocus = function () {
  10480. _this.onCanvasFocusObservable.notifyObservers(_this);
  10481. };
  10482. this._onCanvasBlur = function () {
  10483. _this.onCanvasBlurObservable.notifyObservers(_this);
  10484. };
  10485. canvas.addEventListener("focus", this._onCanvasFocus);
  10486. canvas.addEventListener("blur", this._onCanvasBlur);
  10487. this._onBlur = function () {
  10488. if (_this.disablePerformanceMonitorInBackground) {
  10489. _this._performanceMonitor.disable();
  10490. }
  10491. _this._windowIsBackground = true;
  10492. };
  10493. this._onFocus = function () {
  10494. if (_this.disablePerformanceMonitorInBackground) {
  10495. _this._performanceMonitor.enable();
  10496. }
  10497. _this._windowIsBackground = false;
  10498. };
  10499. this._onCanvasPointerOut = function (ev) {
  10500. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10501. };
  10502. window.addEventListener("blur", this._onBlur);
  10503. window.addEventListener("focus", this._onFocus);
  10504. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10505. // Context lost
  10506. if (!this._doNotHandleContextLost) {
  10507. this._onContextLost = function (evt) {
  10508. evt.preventDefault();
  10509. _this._contextWasLost = true;
  10510. BABYLON.Tools.Warn("WebGL context lost.");
  10511. _this.onContextLostObservable.notifyObservers(_this);
  10512. };
  10513. this._onContextRestored = function (evt) {
  10514. // Adding a timeout to avoid race condition at browser level
  10515. setTimeout(function () {
  10516. // Rebuild gl context
  10517. _this._initGLContext();
  10518. // Rebuild effects
  10519. _this._rebuildEffects();
  10520. // Rebuild textures
  10521. _this._rebuildInternalTextures();
  10522. // Rebuild buffers
  10523. _this._rebuildBuffers();
  10524. // Cache
  10525. _this.wipeCaches(true);
  10526. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10527. _this.onContextRestoredObservable.notifyObservers(_this);
  10528. _this._contextWasLost = false;
  10529. }, 0);
  10530. };
  10531. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10532. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10533. }
  10534. }
  10535. else {
  10536. this._gl = canvasOrContext;
  10537. this._renderingCanvas = this._gl.canvas;
  10538. if (this._gl.renderbufferStorageMultisample) {
  10539. this._webGLVersion = 2.0;
  10540. }
  10541. options.stencil = this._gl.getContextAttributes().stencil;
  10542. }
  10543. // Viewport
  10544. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10545. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10546. this.resize();
  10547. this._isStencilEnable = options.stencil ? true : false;
  10548. this._initGLContext();
  10549. if (canvas) {
  10550. // Fullscreen
  10551. this._onFullscreenChange = function () {
  10552. if (document.fullscreen !== undefined) {
  10553. _this.isFullscreen = document.fullscreen;
  10554. }
  10555. else if (document.mozFullScreen !== undefined) {
  10556. _this.isFullscreen = document.mozFullScreen;
  10557. }
  10558. else if (document.webkitIsFullScreen !== undefined) {
  10559. _this.isFullscreen = document.webkitIsFullScreen;
  10560. }
  10561. else if (document.msIsFullScreen !== undefined) {
  10562. _this.isFullscreen = document.msIsFullScreen;
  10563. }
  10564. // Pointer lock
  10565. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10566. canvas.requestPointerLock = canvas.requestPointerLock ||
  10567. canvas.msRequestPointerLock ||
  10568. canvas.mozRequestPointerLock ||
  10569. canvas.webkitRequestPointerLock;
  10570. if (canvas.requestPointerLock) {
  10571. canvas.requestPointerLock();
  10572. }
  10573. }
  10574. };
  10575. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10576. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10577. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10578. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10579. // Pointer lock
  10580. this._onPointerLockChange = function () {
  10581. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10582. document.webkitPointerLockElement === canvas ||
  10583. document.msPointerLockElement === canvas ||
  10584. document.pointerLockElement === canvas);
  10585. };
  10586. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10587. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10588. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10589. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10590. this._onVRDisplayPointerRestricted = function () {
  10591. if (canvas) {
  10592. canvas.requestPointerLock();
  10593. }
  10594. };
  10595. this._onVRDisplayPointerUnrestricted = function () {
  10596. document.exitPointerLock();
  10597. };
  10598. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10599. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10600. }
  10601. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10602. Engine.audioEngine = new BABYLON.AudioEngine();
  10603. }
  10604. // Prepare buffer pointers
  10605. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10606. this._currentBufferPointers[i] = new BufferPointer();
  10607. }
  10608. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10609. // Load WebVR Devices
  10610. if (options.autoEnableWebVR) {
  10611. this.initWebVR();
  10612. }
  10613. // Detect if we are running on a faulty buggy OS.
  10614. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10615. // Detect if we are running on a faulty buggy desktop OS.
  10616. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10617. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10618. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10619. }
  10620. Object.defineProperty(Engine, "LastCreatedEngine", {
  10621. get: function () {
  10622. if (Engine.Instances.length === 0) {
  10623. return null;
  10624. }
  10625. return Engine.Instances[Engine.Instances.length - 1];
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(Engine, "LastCreatedScene", {
  10631. get: function () {
  10632. var lastCreatedEngine = Engine.LastCreatedEngine;
  10633. if (!lastCreatedEngine) {
  10634. return null;
  10635. }
  10636. if (lastCreatedEngine.scenes.length === 0) {
  10637. return null;
  10638. }
  10639. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. /**
  10645. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10646. */
  10647. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10648. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10649. var engine = Engine.Instances[engineIndex];
  10650. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10651. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10652. }
  10653. }
  10654. };
  10655. Object.defineProperty(Engine, "NEVER", {
  10656. get: function () {
  10657. return Engine._NEVER;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "ALWAYS", {
  10663. get: function () {
  10664. return Engine._ALWAYS;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "LESS", {
  10670. get: function () {
  10671. return Engine._LESS;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "EQUAL", {
  10677. get: function () {
  10678. return Engine._EQUAL;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "LEQUAL", {
  10684. get: function () {
  10685. return Engine._LEQUAL;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "GREATER", {
  10691. get: function () {
  10692. return Engine._GREATER;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "GEQUAL", {
  10698. get: function () {
  10699. return Engine._GEQUAL;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "NOTEQUAL", {
  10705. get: function () {
  10706. return Engine._NOTEQUAL;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "KEEP", {
  10712. get: function () {
  10713. return Engine._KEEP;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "REPLACE", {
  10719. get: function () {
  10720. return Engine._REPLACE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "INCR", {
  10726. get: function () {
  10727. return Engine._INCR;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "DECR", {
  10733. get: function () {
  10734. return Engine._DECR;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "INVERT", {
  10740. get: function () {
  10741. return Engine._INVERT;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "INCR_WRAP", {
  10747. get: function () {
  10748. return Engine._INCR_WRAP;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "DECR_WRAP", {
  10754. get: function () {
  10755. return Engine._DECR_WRAP;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10761. get: function () {
  10762. return Engine._ALPHA_DISABLE;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10768. get: function () {
  10769. return Engine._ALPHA_ONEONE;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "ALPHA_ADD", {
  10775. get: function () {
  10776. return Engine._ALPHA_ADD;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10782. get: function () {
  10783. return Engine._ALPHA_COMBINE;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10789. get: function () {
  10790. return Engine._ALPHA_SUBTRACT;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10796. get: function () {
  10797. return Engine._ALPHA_MULTIPLY;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10803. get: function () {
  10804. return Engine._ALPHA_MAXIMIZED;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10810. get: function () {
  10811. return Engine._ALPHA_PREMULTIPLIED;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10817. get: function () {
  10818. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10824. get: function () {
  10825. return Engine._ALPHA_INTERPOLATE;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10831. get: function () {
  10832. return Engine._ALPHA_SCREENMODE;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10838. get: function () {
  10839. return Engine._DELAYLOADSTATE_NONE;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10845. get: function () {
  10846. return Engine._DELAYLOADSTATE_LOADED;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10852. get: function () {
  10853. return Engine._DELAYLOADSTATE_LOADING;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10859. get: function () {
  10860. return Engine._DELAYLOADSTATE_NOTLOADED;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10866. get: function () {
  10867. return Engine._TEXTUREFORMAT_ALPHA;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10873. get: function () {
  10874. return Engine._TEXTUREFORMAT_LUMINANCE;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10880. /**
  10881. * R32F
  10882. */
  10883. get: function () {
  10884. return Engine._TEXTUREFORMAT_R32F;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10890. /**
  10891. * RG32F
  10892. */
  10893. get: function () {
  10894. return Engine._TEXTUREFORMAT_RG32F;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10900. /**
  10901. * RGB32F
  10902. */
  10903. get: function () {
  10904. return Engine._TEXTUREFORMAT_RGB32F;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10910. /**
  10911. * RGBA32F
  10912. */
  10913. get: function () {
  10914. return Engine._TEXTUREFORMAT_RGBA32F;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10920. get: function () {
  10921. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10927. get: function () {
  10928. return Engine._TEXTUREFORMAT_RGB;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10934. get: function () {
  10935. return Engine._TEXTUREFORMAT_RGBA;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10941. get: function () {
  10942. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10948. get: function () {
  10949. return Engine._TEXTURETYPE_FLOAT;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10955. get: function () {
  10956. return Engine._TEXTURETYPE_HALF_FLOAT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10962. get: function () {
  10963. return Engine._SCALEMODE_FLOOR;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10969. get: function () {
  10970. return Engine._SCALEMODE_NEAREST;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10976. get: function () {
  10977. return Engine._SCALEMODE_CEILING;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "Version", {
  10983. get: function () {
  10984. return "3.2.0-alpha8";
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10990. get: function () {
  10991. return this._vrExclusivePointerMode;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10997. get: function () {
  10998. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11004. get: function () {
  11005. return this._webGLVersion < 2 || this.forcePOTTextures;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine.prototype, "badOS", {
  11011. get: function () {
  11012. return this._badOS;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11018. get: function () {
  11019. return this._badDesktopOS;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11025. get: function () {
  11026. return this._performanceMonitor;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11032. get: function () {
  11033. return this._texturesSupported;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11039. get: function () {
  11040. return this._textureFormatInUse;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine.prototype, "currentViewport", {
  11046. get: function () {
  11047. return this._cachedViewport;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11053. // Empty texture
  11054. get: function () {
  11055. if (!this._emptyTexture) {
  11056. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11057. }
  11058. return this._emptyTexture;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11064. get: function () {
  11065. if (!this._emptyTexture3D) {
  11066. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11067. }
  11068. return this._emptyTexture3D;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11074. get: function () {
  11075. if (!this._emptyCubeTexture) {
  11076. var faceData = new Uint8Array(4);
  11077. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11078. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11079. }
  11080. return this._emptyCubeTexture;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Engine.prototype._rebuildInternalTextures = function () {
  11086. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11087. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11088. var internalTexture = currentState_1[_i];
  11089. internalTexture._rebuild();
  11090. }
  11091. };
  11092. Engine.prototype._rebuildEffects = function () {
  11093. for (var key in this._compiledEffects) {
  11094. var effect = this._compiledEffects[key];
  11095. effect._prepareEffect();
  11096. }
  11097. BABYLON.Effect.ResetCache();
  11098. };
  11099. Engine.prototype._rebuildBuffers = function () {
  11100. // Index / Vertex
  11101. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11102. var scene = _a[_i];
  11103. scene.resetCachedMaterial();
  11104. scene._rebuildGeometries();
  11105. scene._rebuildTextures();
  11106. }
  11107. // Uniforms
  11108. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11109. var uniformBuffer = _c[_b];
  11110. uniformBuffer._rebuild();
  11111. }
  11112. };
  11113. Engine.prototype._initGLContext = function () {
  11114. // Caps
  11115. this._caps = new EngineCapabilities();
  11116. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11117. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11118. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11119. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11120. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11121. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11122. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11123. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11124. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11125. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11126. // Infos
  11127. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11128. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11129. if (rendererInfo != null) {
  11130. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11131. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11132. }
  11133. if (!this._glVendor) {
  11134. this._glVendor = "Unknown vendor";
  11135. }
  11136. if (!this._glRenderer) {
  11137. this._glRenderer = "Unknown renderer";
  11138. }
  11139. // Constants
  11140. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11141. if (this._gl.RGBA16F !== 0x881A) {
  11142. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11143. }
  11144. if (this._gl.RGBA32F !== 0x8814) {
  11145. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11146. }
  11147. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11148. this._gl.DEPTH24_STENCIL8 = 35056;
  11149. }
  11150. // Extensions
  11151. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11152. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11153. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11154. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11155. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11156. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11157. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11158. 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');
  11159. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11160. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11161. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11162. this._caps.highPrecisionShaderSupported = true;
  11163. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11164. if (this._caps.timerQuery) {
  11165. if (this._webGLVersion === 1) {
  11166. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11167. }
  11168. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11169. }
  11170. // Checks if some of the format renders first to allow the use of webgl inspector.
  11171. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11172. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11173. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11174. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11175. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11176. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11177. if (this._webGLVersion > 1) {
  11178. this._gl.HALF_FLOAT_OES = 0x140B;
  11179. }
  11180. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11181. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11182. // Draw buffers
  11183. if (this._webGLVersion > 1) {
  11184. this._caps.drawBuffersExtension = true;
  11185. }
  11186. else {
  11187. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11188. if (drawBuffersExtension !== null) {
  11189. this._caps.drawBuffersExtension = true;
  11190. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11191. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11192. for (var i = 0; i < 16; i++) {
  11193. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11194. }
  11195. }
  11196. else {
  11197. this._caps.drawBuffersExtension = false;
  11198. }
  11199. }
  11200. // Depth Texture
  11201. if (this._webGLVersion > 1) {
  11202. this._caps.depthTextureExtension = true;
  11203. }
  11204. else {
  11205. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11206. if (depthTextureExtension != null) {
  11207. this._caps.depthTextureExtension = true;
  11208. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11209. }
  11210. }
  11211. // Vertex array object
  11212. if (this._webGLVersion > 1) {
  11213. this._caps.vertexArrayObject = true;
  11214. }
  11215. else {
  11216. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11217. if (vertexArrayObjectExtension != null) {
  11218. this._caps.vertexArrayObject = true;
  11219. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11220. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11221. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11222. }
  11223. else {
  11224. this._caps.vertexArrayObject = false;
  11225. }
  11226. }
  11227. // Instances count
  11228. if (this._webGLVersion > 1) {
  11229. this._caps.instancedArrays = true;
  11230. }
  11231. else {
  11232. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11233. if (instanceExtension != null) {
  11234. this._caps.instancedArrays = true;
  11235. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11236. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11237. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11238. }
  11239. else {
  11240. this._caps.instancedArrays = false;
  11241. }
  11242. }
  11243. // Intelligently add supported compressed formats in order to check for.
  11244. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11245. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11246. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11247. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11248. if (this._caps.astc)
  11249. this.texturesSupported.push('-astc.ktx');
  11250. if (this._caps.s3tc)
  11251. this.texturesSupported.push('-dxt.ktx');
  11252. if (this._caps.pvrtc)
  11253. this.texturesSupported.push('-pvrtc.ktx');
  11254. if (this._caps.etc2)
  11255. this.texturesSupported.push('-etc2.ktx');
  11256. if (this._caps.etc1)
  11257. this.texturesSupported.push('-etc1.ktx');
  11258. if (this._gl.getShaderPrecisionFormat) {
  11259. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11260. if (highp) {
  11261. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11262. }
  11263. }
  11264. // Depth buffer
  11265. this.setDepthBuffer(true);
  11266. this.setDepthFunctionToLessOrEqual();
  11267. this.setDepthWrite(true);
  11268. // Texture maps
  11269. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11270. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11271. this._nextFreeTextureSlots.push(slot);
  11272. }
  11273. };
  11274. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11275. get: function () {
  11276. return this._webGLVersion;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11282. /**
  11283. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11284. */
  11285. get: function () {
  11286. return this._isStencilEnable;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Engine.prototype._prepareWorkingCanvas = function () {
  11292. if (this._workingCanvas) {
  11293. return;
  11294. }
  11295. this._workingCanvas = document.createElement("canvas");
  11296. var context = this._workingCanvas.getContext("2d");
  11297. if (context) {
  11298. this._workingContext = context;
  11299. }
  11300. };
  11301. Engine.prototype.resetTextureCache = function () {
  11302. for (var key in this._boundTexturesCache) {
  11303. var boundTexture = this._boundTexturesCache[key];
  11304. if (boundTexture) {
  11305. this._removeDesignatedSlot(boundTexture);
  11306. }
  11307. this._boundTexturesCache[key] = null;
  11308. }
  11309. if (!this.disableTextureBindingOptimization) {
  11310. this._nextFreeTextureSlots = [];
  11311. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11312. this._nextFreeTextureSlots.push(slot);
  11313. }
  11314. }
  11315. this._currentTextureChannel = -1;
  11316. };
  11317. Engine.prototype.isDeterministicLockStep = function () {
  11318. return this._deterministicLockstep;
  11319. };
  11320. Engine.prototype.getLockstepMaxSteps = function () {
  11321. return this._lockstepMaxSteps;
  11322. };
  11323. Engine.prototype.getGlInfo = function () {
  11324. return {
  11325. vendor: this._glVendor,
  11326. renderer: this._glRenderer,
  11327. version: this._glVersion
  11328. };
  11329. };
  11330. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11331. if (useScreen === void 0) { useScreen = false; }
  11332. var viewport = camera.viewport;
  11333. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11334. };
  11335. Engine.prototype.getRenderWidth = function (useScreen) {
  11336. if (useScreen === void 0) { useScreen = false; }
  11337. if (!useScreen && this._currentRenderTarget) {
  11338. return this._currentRenderTarget.width;
  11339. }
  11340. return this._gl.drawingBufferWidth;
  11341. };
  11342. Engine.prototype.getRenderHeight = function (useScreen) {
  11343. if (useScreen === void 0) { useScreen = false; }
  11344. if (!useScreen && this._currentRenderTarget) {
  11345. return this._currentRenderTarget.height;
  11346. }
  11347. return this._gl.drawingBufferHeight;
  11348. };
  11349. Engine.prototype.getRenderingCanvas = function () {
  11350. return this._renderingCanvas;
  11351. };
  11352. Engine.prototype.getRenderingCanvasClientRect = function () {
  11353. if (!this._renderingCanvas) {
  11354. return null;
  11355. }
  11356. return this._renderingCanvas.getBoundingClientRect();
  11357. };
  11358. Engine.prototype.setHardwareScalingLevel = function (level) {
  11359. this._hardwareScalingLevel = level;
  11360. this.resize();
  11361. };
  11362. Engine.prototype.getHardwareScalingLevel = function () {
  11363. return this._hardwareScalingLevel;
  11364. };
  11365. Engine.prototype.getLoadedTexturesCache = function () {
  11366. return this._internalTexturesCache;
  11367. };
  11368. Engine.prototype.getCaps = function () {
  11369. return this._caps;
  11370. };
  11371. Object.defineProperty(Engine.prototype, "drawCalls", {
  11372. /** The number of draw calls submitted last frame */
  11373. get: function () {
  11374. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11375. return 0;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11381. get: function () {
  11382. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11383. return null;
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. Engine.prototype.getDepthFunction = function () {
  11389. return this._depthCullingState.depthFunc;
  11390. };
  11391. Engine.prototype.setDepthFunction = function (depthFunc) {
  11392. this._depthCullingState.depthFunc = depthFunc;
  11393. };
  11394. Engine.prototype.setDepthFunctionToGreater = function () {
  11395. this._depthCullingState.depthFunc = this._gl.GREATER;
  11396. };
  11397. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11398. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11399. };
  11400. Engine.prototype.setDepthFunctionToLess = function () {
  11401. this._depthCullingState.depthFunc = this._gl.LESS;
  11402. };
  11403. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11404. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11405. };
  11406. Engine.prototype.getStencilBuffer = function () {
  11407. return this._stencilState.stencilTest;
  11408. };
  11409. Engine.prototype.setStencilBuffer = function (enable) {
  11410. this._stencilState.stencilTest = enable;
  11411. };
  11412. Engine.prototype.getStencilMask = function () {
  11413. return this._stencilState.stencilMask;
  11414. };
  11415. Engine.prototype.setStencilMask = function (mask) {
  11416. this._stencilState.stencilMask = mask;
  11417. };
  11418. Engine.prototype.getStencilFunction = function () {
  11419. return this._stencilState.stencilFunc;
  11420. };
  11421. Engine.prototype.getStencilFunctionReference = function () {
  11422. return this._stencilState.stencilFuncRef;
  11423. };
  11424. Engine.prototype.getStencilFunctionMask = function () {
  11425. return this._stencilState.stencilFuncMask;
  11426. };
  11427. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11428. this._stencilState.stencilFunc = stencilFunc;
  11429. };
  11430. Engine.prototype.setStencilFunctionReference = function (reference) {
  11431. this._stencilState.stencilFuncRef = reference;
  11432. };
  11433. Engine.prototype.setStencilFunctionMask = function (mask) {
  11434. this._stencilState.stencilFuncMask = mask;
  11435. };
  11436. Engine.prototype.getStencilOperationFail = function () {
  11437. return this._stencilState.stencilOpStencilFail;
  11438. };
  11439. Engine.prototype.getStencilOperationDepthFail = function () {
  11440. return this._stencilState.stencilOpDepthFail;
  11441. };
  11442. Engine.prototype.getStencilOperationPass = function () {
  11443. return this._stencilState.stencilOpStencilDepthPass;
  11444. };
  11445. Engine.prototype.setStencilOperationFail = function (operation) {
  11446. this._stencilState.stencilOpStencilFail = operation;
  11447. };
  11448. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11449. this._stencilState.stencilOpDepthFail = operation;
  11450. };
  11451. Engine.prototype.setStencilOperationPass = function (operation) {
  11452. this._stencilState.stencilOpStencilDepthPass = operation;
  11453. };
  11454. Engine.prototype.setDitheringState = function (value) {
  11455. if (value) {
  11456. this._gl.enable(this._gl.DITHER);
  11457. }
  11458. else {
  11459. this._gl.disable(this._gl.DITHER);
  11460. }
  11461. };
  11462. Engine.prototype.setRasterizerState = function (value) {
  11463. if (value) {
  11464. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11465. }
  11466. else {
  11467. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11468. }
  11469. };
  11470. /**
  11471. * stop executing a render loop function and remove it from the execution array
  11472. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11473. */
  11474. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11475. if (!renderFunction) {
  11476. this._activeRenderLoops = [];
  11477. return;
  11478. }
  11479. var index = this._activeRenderLoops.indexOf(renderFunction);
  11480. if (index >= 0) {
  11481. this._activeRenderLoops.splice(index, 1);
  11482. }
  11483. };
  11484. Engine.prototype._renderLoop = function () {
  11485. if (!this._contextWasLost) {
  11486. var shouldRender = true;
  11487. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11488. shouldRender = false;
  11489. }
  11490. if (shouldRender) {
  11491. // Start new frame
  11492. this.beginFrame();
  11493. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11494. var renderFunction = this._activeRenderLoops[index];
  11495. renderFunction();
  11496. }
  11497. // Present
  11498. this.endFrame();
  11499. }
  11500. }
  11501. if (this._activeRenderLoops.length > 0) {
  11502. // Register new frame
  11503. var requester = null;
  11504. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11505. requester = this._vrDisplay;
  11506. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11507. }
  11508. else {
  11509. this._renderingQueueLaunched = false;
  11510. }
  11511. };
  11512. /**
  11513. * Register and execute a render loop. The engine can have more than one render function.
  11514. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11515. * @example
  11516. * engine.runRenderLoop(function () {
  11517. * scene.render()
  11518. * })
  11519. */
  11520. Engine.prototype.runRenderLoop = function (renderFunction) {
  11521. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11522. return;
  11523. }
  11524. this._activeRenderLoops.push(renderFunction);
  11525. if (!this._renderingQueueLaunched) {
  11526. this._renderingQueueLaunched = true;
  11527. this._bindedRenderFunction = this._renderLoop.bind(this);
  11528. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11529. }
  11530. };
  11531. /**
  11532. * Toggle full screen mode.
  11533. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11534. * @param {any} options - an options object to be sent to the requestFullscreen function
  11535. */
  11536. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11537. if (this.isFullscreen) {
  11538. BABYLON.Tools.ExitFullscreen();
  11539. }
  11540. else {
  11541. this._pointerLockRequested = requestPointerLock;
  11542. if (this._renderingCanvas) {
  11543. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11544. }
  11545. }
  11546. };
  11547. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11548. if (stencil === void 0) { stencil = false; }
  11549. this.applyStates();
  11550. var mode = 0;
  11551. if (backBuffer && color) {
  11552. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11553. mode |= this._gl.COLOR_BUFFER_BIT;
  11554. }
  11555. if (depth) {
  11556. this._gl.clearDepth(1.0);
  11557. mode |= this._gl.DEPTH_BUFFER_BIT;
  11558. }
  11559. if (stencil) {
  11560. this._gl.clearStencil(0);
  11561. mode |= this._gl.STENCIL_BUFFER_BIT;
  11562. }
  11563. this._gl.clear(mode);
  11564. };
  11565. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11566. var gl = this._gl;
  11567. // Save state
  11568. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11569. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11570. // Change state
  11571. gl.enable(gl.SCISSOR_TEST);
  11572. gl.scissor(x, y, width, height);
  11573. // Clear
  11574. this.clear(clearColor, true, true, true);
  11575. // Restore state
  11576. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11577. if (curScissor === true) {
  11578. gl.enable(gl.SCISSOR_TEST);
  11579. }
  11580. else {
  11581. gl.disable(gl.SCISSOR_TEST);
  11582. }
  11583. };
  11584. /**
  11585. * Set the WebGL's viewport
  11586. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11587. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11588. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11589. */
  11590. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11591. var width = requiredWidth || this.getRenderWidth();
  11592. var height = requiredHeight || this.getRenderHeight();
  11593. var x = viewport.x || 0;
  11594. var y = viewport.y || 0;
  11595. this._cachedViewport = viewport;
  11596. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11597. };
  11598. /**
  11599. * Directly set the WebGL Viewport
  11600. * The x, y, width & height are directly passed to the WebGL call
  11601. * @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.
  11602. */
  11603. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11604. var currentViewport = this._cachedViewport;
  11605. this._cachedViewport = null;
  11606. this._gl.viewport(x, y, width, height);
  11607. return currentViewport;
  11608. };
  11609. Engine.prototype.beginFrame = function () {
  11610. this.onBeginFrameObservable.notifyObservers(this);
  11611. this._measureFps();
  11612. };
  11613. Engine.prototype.endFrame = function () {
  11614. //force a flush in case we are using a bad OS.
  11615. if (this._badOS) {
  11616. this.flushFramebuffer();
  11617. }
  11618. //submit frame to the vr device, if enabled
  11619. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11620. // TODO: We should only submit the frame if we read frameData successfully.
  11621. this._vrDisplay.submitFrame();
  11622. }
  11623. this.onEndFrameObservable.notifyObservers(this);
  11624. };
  11625. /**
  11626. * resize the view according to the canvas' size.
  11627. * @example
  11628. * window.addEventListener("resize", function () {
  11629. * engine.resize();
  11630. * });
  11631. */
  11632. Engine.prototype.resize = function () {
  11633. // We're not resizing the size of the canvas while in VR mode & presenting
  11634. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11635. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11636. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11637. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11638. }
  11639. };
  11640. /**
  11641. * force a specific size of the canvas
  11642. * @param {number} width - the new canvas' width
  11643. * @param {number} height - the new canvas' height
  11644. */
  11645. Engine.prototype.setSize = function (width, height) {
  11646. if (!this._renderingCanvas) {
  11647. return;
  11648. }
  11649. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11650. return;
  11651. }
  11652. this._renderingCanvas.width = width;
  11653. this._renderingCanvas.height = height;
  11654. for (var index = 0; index < this.scenes.length; index++) {
  11655. var scene = this.scenes[index];
  11656. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11657. var cam = scene.cameras[camIndex];
  11658. cam._currentRenderId = 0;
  11659. }
  11660. }
  11661. if (this.onResizeObservable.hasObservers) {
  11662. this.onResizeObservable.notifyObservers(this);
  11663. }
  11664. };
  11665. // WebVR functions
  11666. Engine.prototype.isVRDevicePresent = function () {
  11667. return !!this._vrDisplay;
  11668. };
  11669. Engine.prototype.getVRDevice = function () {
  11670. return this._vrDisplay;
  11671. };
  11672. /**
  11673. * Initializes a webVR display and starts listening to display change events.
  11674. * The onVRDisplayChangedObservable will be notified upon these changes.
  11675. * @returns The onVRDisplayChangedObservable.
  11676. */
  11677. Engine.prototype.initWebVR = function () {
  11678. this.initWebVRAsync();
  11679. return this.onVRDisplayChangedObservable;
  11680. };
  11681. /**
  11682. * Initializes a webVR display and starts listening to display change events.
  11683. * The onVRDisplayChangedObservable will be notified upon these changes.
  11684. * @returns A promise containing a VRDisplay and if vr is supported.
  11685. */
  11686. Engine.prototype.initWebVRAsync = function () {
  11687. var _this = this;
  11688. var notifyObservers = function () {
  11689. var eventArgs = {
  11690. vrDisplay: _this._vrDisplay,
  11691. vrSupported: _this._vrSupported
  11692. };
  11693. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11694. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11695. };
  11696. if (!this._onVrDisplayConnect) {
  11697. this._onVrDisplayConnect = function (event) {
  11698. _this._vrDisplay = event.display;
  11699. notifyObservers();
  11700. };
  11701. this._onVrDisplayDisconnect = function () {
  11702. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11703. _this._vrDisplay = undefined;
  11704. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11705. notifyObservers();
  11706. };
  11707. this._onVrDisplayPresentChange = function () {
  11708. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11709. };
  11710. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11711. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11712. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11713. }
  11714. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11715. this._webVRInitPromise.then(notifyObservers);
  11716. return this._webVRInitPromise;
  11717. };
  11718. Engine.prototype.enableVR = function () {
  11719. var _this = this;
  11720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11721. var onResolved = function () {
  11722. _this.onVRRequestPresentComplete.notifyObservers(true);
  11723. _this._onVRFullScreenTriggered();
  11724. };
  11725. var onRejected = function () {
  11726. _this.onVRRequestPresentComplete.notifyObservers(false);
  11727. };
  11728. this.onVRRequestPresentStart.notifyObservers(this);
  11729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11730. }
  11731. };
  11732. Engine.prototype.disableVR = function () {
  11733. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11734. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11735. }
  11736. };
  11737. Engine.prototype._getVRDisplaysAsync = function () {
  11738. var _this = this;
  11739. return new Promise(function (res, rej) {
  11740. if (navigator.getVRDisplays) {
  11741. navigator.getVRDisplays().then(function (devices) {
  11742. _this._vrSupported = true;
  11743. // note that devices may actually be an empty array. This is fine;
  11744. // we expect this._vrDisplay to be undefined in this case.
  11745. _this._vrDisplay = devices[0];
  11746. res({
  11747. vrDisplay: _this._vrDisplay,
  11748. vrSupported: _this._vrSupported
  11749. });
  11750. });
  11751. }
  11752. else {
  11753. _this._vrDisplay = undefined;
  11754. _this._vrSupported = false;
  11755. res({
  11756. vrDisplay: _this._vrDisplay,
  11757. vrSupported: _this._vrSupported
  11758. });
  11759. }
  11760. });
  11761. };
  11762. /**
  11763. * Binds the frame buffer to the specified texture.
  11764. * @param texture The texture to render to or null for the default canvas
  11765. * @param faceIndex The face of the texture to render to in case of cube texture
  11766. * @param requiredWidth The width of the target to render to
  11767. * @param requiredHeight The height of the target to render to
  11768. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11769. * @param depthStencilTexture The depth stencil texture to use to render
  11770. */
  11771. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11772. if (this._currentRenderTarget) {
  11773. this.unBindFramebuffer(this._currentRenderTarget);
  11774. }
  11775. this._currentRenderTarget = texture;
  11776. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11777. var gl = this._gl;
  11778. if (texture.isCube) {
  11779. if (faceIndex === undefined) {
  11780. faceIndex = 0;
  11781. }
  11782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11783. if (depthStencilTexture) {
  11784. if (depthStencilTexture._generateStencilBuffer) {
  11785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11786. }
  11787. else {
  11788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11789. }
  11790. }
  11791. }
  11792. if (this._cachedViewport && !forceFullscreenViewport) {
  11793. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11794. }
  11795. else {
  11796. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11797. }
  11798. this.wipeCaches();
  11799. };
  11800. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11801. if (this._currentFramebuffer !== framebuffer) {
  11802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11803. this._currentFramebuffer = framebuffer;
  11804. }
  11805. };
  11806. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11807. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11808. this._currentRenderTarget = null;
  11809. // If MSAA, we need to bitblt back to main texture
  11810. var gl = this._gl;
  11811. if (texture._MSAAFramebuffer) {
  11812. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11813. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11814. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11815. }
  11816. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11817. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11818. gl.generateMipmap(gl.TEXTURE_2D);
  11819. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11820. }
  11821. if (onBeforeUnbind) {
  11822. if (texture._MSAAFramebuffer) {
  11823. // Bind the correct framebuffer
  11824. this.bindUnboundFramebuffer(texture._framebuffer);
  11825. }
  11826. onBeforeUnbind();
  11827. }
  11828. this.bindUnboundFramebuffer(null);
  11829. };
  11830. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11831. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11832. this._currentRenderTarget = null;
  11833. // If MSAA, we need to bitblt back to main texture
  11834. var gl = this._gl;
  11835. if (textures[0]._MSAAFramebuffer) {
  11836. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11837. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11838. var attachments = textures[0]._attachments;
  11839. if (!attachments) {
  11840. attachments = new Array(textures.length);
  11841. textures[0]._attachments = attachments;
  11842. }
  11843. for (var i = 0; i < textures.length; i++) {
  11844. var texture = textures[i];
  11845. for (var j = 0; j < attachments.length; j++) {
  11846. attachments[j] = gl.NONE;
  11847. }
  11848. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11849. gl.readBuffer(attachments[i]);
  11850. gl.drawBuffers(attachments);
  11851. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11852. }
  11853. for (var i = 0; i < attachments.length; i++) {
  11854. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11855. }
  11856. gl.drawBuffers(attachments);
  11857. }
  11858. for (var i = 0; i < textures.length; i++) {
  11859. var texture = textures[i];
  11860. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11861. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11862. gl.generateMipmap(gl.TEXTURE_2D);
  11863. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11864. }
  11865. }
  11866. if (onBeforeUnbind) {
  11867. if (textures[0]._MSAAFramebuffer) {
  11868. // Bind the correct framebuffer
  11869. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11870. }
  11871. onBeforeUnbind();
  11872. }
  11873. this.bindUnboundFramebuffer(null);
  11874. };
  11875. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11876. if (texture.generateMipMaps) {
  11877. var gl = this._gl;
  11878. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11879. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11880. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11881. }
  11882. };
  11883. Engine.prototype.flushFramebuffer = function () {
  11884. this._gl.flush();
  11885. };
  11886. Engine.prototype.restoreDefaultFramebuffer = function () {
  11887. if (this._currentRenderTarget) {
  11888. this.unBindFramebuffer(this._currentRenderTarget);
  11889. }
  11890. else {
  11891. this.bindUnboundFramebuffer(null);
  11892. }
  11893. if (this._cachedViewport) {
  11894. this.setViewport(this._cachedViewport);
  11895. }
  11896. this.wipeCaches();
  11897. };
  11898. // UBOs
  11899. Engine.prototype.createUniformBuffer = function (elements) {
  11900. var ubo = this._gl.createBuffer();
  11901. if (!ubo) {
  11902. throw new Error("Unable to create uniform buffer");
  11903. }
  11904. this.bindUniformBuffer(ubo);
  11905. if (elements instanceof Float32Array) {
  11906. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11907. }
  11908. else {
  11909. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11910. }
  11911. this.bindUniformBuffer(null);
  11912. ubo.references = 1;
  11913. return ubo;
  11914. };
  11915. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11916. var ubo = this._gl.createBuffer();
  11917. if (!ubo) {
  11918. throw new Error("Unable to create dynamic uniform buffer");
  11919. }
  11920. this.bindUniformBuffer(ubo);
  11921. if (elements instanceof Float32Array) {
  11922. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11923. }
  11924. else {
  11925. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11926. }
  11927. this.bindUniformBuffer(null);
  11928. ubo.references = 1;
  11929. return ubo;
  11930. };
  11931. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11932. this.bindUniformBuffer(uniformBuffer);
  11933. if (offset === undefined) {
  11934. offset = 0;
  11935. }
  11936. if (count === undefined) {
  11937. if (elements instanceof Float32Array) {
  11938. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11939. }
  11940. else {
  11941. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11942. }
  11943. }
  11944. else {
  11945. if (elements instanceof Float32Array) {
  11946. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11947. }
  11948. else {
  11949. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11950. }
  11951. }
  11952. this.bindUniformBuffer(null);
  11953. };
  11954. // VBOs
  11955. Engine.prototype._resetVertexBufferBinding = function () {
  11956. this.bindArrayBuffer(null);
  11957. this._cachedVertexBuffers = null;
  11958. };
  11959. Engine.prototype.createVertexBuffer = function (vertices) {
  11960. var vbo = this._gl.createBuffer();
  11961. if (!vbo) {
  11962. throw new Error("Unable to create vertex buffer");
  11963. }
  11964. this.bindArrayBuffer(vbo);
  11965. if (vertices instanceof Float32Array) {
  11966. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11967. }
  11968. else {
  11969. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11970. }
  11971. this._resetVertexBufferBinding();
  11972. vbo.references = 1;
  11973. return vbo;
  11974. };
  11975. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11976. var vbo = this._gl.createBuffer();
  11977. if (!vbo) {
  11978. throw new Error("Unable to create dynamic vertex buffer");
  11979. }
  11980. this.bindArrayBuffer(vbo);
  11981. if (vertices instanceof Float32Array) {
  11982. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11983. }
  11984. else {
  11985. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11986. }
  11987. this._resetVertexBufferBinding();
  11988. vbo.references = 1;
  11989. return vbo;
  11990. };
  11991. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11992. if (offset === void 0) { offset = 0; }
  11993. // Force cache update
  11994. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11995. this.bindIndexBuffer(indexBuffer);
  11996. var arrayBuffer;
  11997. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11998. arrayBuffer = indices;
  11999. }
  12000. else {
  12001. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12002. }
  12003. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12004. this._resetIndexBufferBinding();
  12005. };
  12006. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12007. this.bindArrayBuffer(vertexBuffer);
  12008. if (offset === undefined) {
  12009. offset = 0;
  12010. }
  12011. if (count === undefined) {
  12012. if (vertices instanceof Float32Array) {
  12013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12014. }
  12015. else {
  12016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12017. }
  12018. }
  12019. else {
  12020. if (vertices instanceof Float32Array) {
  12021. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12022. }
  12023. else {
  12024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12025. }
  12026. }
  12027. this._resetVertexBufferBinding();
  12028. };
  12029. Engine.prototype._resetIndexBufferBinding = function () {
  12030. this.bindIndexBuffer(null);
  12031. this._cachedIndexBuffer = null;
  12032. };
  12033. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12034. var vbo = this._gl.createBuffer();
  12035. if (!vbo) {
  12036. throw new Error("Unable to create index buffer");
  12037. }
  12038. this.bindIndexBuffer(vbo);
  12039. // Check for 32 bits indices
  12040. var arrayBuffer;
  12041. var need32Bits = false;
  12042. if (indices instanceof Uint16Array) {
  12043. arrayBuffer = indices;
  12044. }
  12045. else {
  12046. //check 32 bit support
  12047. if (this._caps.uintIndices) {
  12048. if (indices instanceof Uint32Array) {
  12049. arrayBuffer = indices;
  12050. need32Bits = true;
  12051. }
  12052. else {
  12053. //number[] or Int32Array, check if 32 bit is necessary
  12054. for (var index = 0; index < indices.length; index++) {
  12055. if (indices[index] > 65535) {
  12056. need32Bits = true;
  12057. break;
  12058. }
  12059. }
  12060. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12061. }
  12062. }
  12063. else {
  12064. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12065. arrayBuffer = new Uint16Array(indices);
  12066. }
  12067. }
  12068. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12069. this._resetIndexBufferBinding();
  12070. vbo.references = 1;
  12071. vbo.is32Bits = need32Bits;
  12072. return vbo;
  12073. };
  12074. Engine.prototype.bindArrayBuffer = function (buffer) {
  12075. if (!this._vaoRecordInProgress) {
  12076. this._unbindVertexArrayObject();
  12077. }
  12078. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12079. };
  12080. Engine.prototype.bindUniformBuffer = function (buffer) {
  12081. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12082. };
  12083. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12084. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12085. };
  12086. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12087. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12088. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12089. };
  12090. ;
  12091. Engine.prototype.bindIndexBuffer = function (buffer) {
  12092. if (!this._vaoRecordInProgress) {
  12093. this._unbindVertexArrayObject();
  12094. }
  12095. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12096. };
  12097. Engine.prototype.bindBuffer = function (buffer, target) {
  12098. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12099. this._gl.bindBuffer(target, buffer);
  12100. this._currentBoundBuffer[target] = buffer;
  12101. }
  12102. };
  12103. Engine.prototype.updateArrayBuffer = function (data) {
  12104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12105. };
  12106. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12107. var pointer = this._currentBufferPointers[indx];
  12108. var changed = false;
  12109. if (!pointer.active) {
  12110. changed = true;
  12111. pointer.active = true;
  12112. pointer.index = indx;
  12113. pointer.size = size;
  12114. pointer.type = type;
  12115. pointer.normalized = normalized;
  12116. pointer.stride = stride;
  12117. pointer.offset = offset;
  12118. pointer.buffer = buffer;
  12119. }
  12120. else {
  12121. if (pointer.buffer !== buffer) {
  12122. pointer.buffer = buffer;
  12123. changed = true;
  12124. }
  12125. if (pointer.size !== size) {
  12126. pointer.size = size;
  12127. changed = true;
  12128. }
  12129. if (pointer.type !== type) {
  12130. pointer.type = type;
  12131. changed = true;
  12132. }
  12133. if (pointer.normalized !== normalized) {
  12134. pointer.normalized = normalized;
  12135. changed = true;
  12136. }
  12137. if (pointer.stride !== stride) {
  12138. pointer.stride = stride;
  12139. changed = true;
  12140. }
  12141. if (pointer.offset !== offset) {
  12142. pointer.offset = offset;
  12143. changed = true;
  12144. }
  12145. }
  12146. if (changed || this._vaoRecordInProgress) {
  12147. this.bindArrayBuffer(buffer);
  12148. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12149. }
  12150. };
  12151. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12152. if (indexBuffer == null) {
  12153. return;
  12154. }
  12155. if (this._cachedIndexBuffer !== indexBuffer) {
  12156. this._cachedIndexBuffer = indexBuffer;
  12157. this.bindIndexBuffer(indexBuffer);
  12158. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12159. }
  12160. };
  12161. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12162. var attributes = effect.getAttributesNames();
  12163. if (!this._vaoRecordInProgress) {
  12164. this._unbindVertexArrayObject();
  12165. }
  12166. this.unbindAllAttributes();
  12167. for (var index = 0; index < attributes.length; index++) {
  12168. var order = effect.getAttributeLocation(index);
  12169. if (order >= 0) {
  12170. var vertexBuffer = vertexBuffers[attributes[index]];
  12171. if (!vertexBuffer) {
  12172. continue;
  12173. }
  12174. this._gl.enableVertexAttribArray(order);
  12175. if (!this._vaoRecordInProgress) {
  12176. this._vertexAttribArraysEnabled[order] = true;
  12177. }
  12178. var buffer = vertexBuffer.getBuffer();
  12179. if (buffer) {
  12180. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12181. if (vertexBuffer.getIsInstanced()) {
  12182. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12183. if (!this._vaoRecordInProgress) {
  12184. this._currentInstanceLocations.push(order);
  12185. this._currentInstanceBuffers.push(buffer);
  12186. }
  12187. }
  12188. }
  12189. }
  12190. }
  12191. };
  12192. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12193. var vao = this._gl.createVertexArray();
  12194. this._vaoRecordInProgress = true;
  12195. this._gl.bindVertexArray(vao);
  12196. this._mustWipeVertexAttributes = true;
  12197. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12198. this.bindIndexBuffer(indexBuffer);
  12199. this._vaoRecordInProgress = false;
  12200. this._gl.bindVertexArray(null);
  12201. return vao;
  12202. };
  12203. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12204. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12205. this._cachedVertexArrayObject = vertexArrayObject;
  12206. this._gl.bindVertexArray(vertexArrayObject);
  12207. this._cachedVertexBuffers = null;
  12208. this._cachedIndexBuffer = null;
  12209. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12210. this._mustWipeVertexAttributes = true;
  12211. }
  12212. };
  12213. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12214. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12215. this._cachedVertexBuffers = vertexBuffer;
  12216. this._cachedEffectForVertexBuffers = effect;
  12217. var attributesCount = effect.getAttributesCount();
  12218. this._unbindVertexArrayObject();
  12219. this.unbindAllAttributes();
  12220. var offset = 0;
  12221. for (var index = 0; index < attributesCount; index++) {
  12222. if (index < vertexDeclaration.length) {
  12223. var order = effect.getAttributeLocation(index);
  12224. if (order >= 0) {
  12225. this._gl.enableVertexAttribArray(order);
  12226. this._vertexAttribArraysEnabled[order] = true;
  12227. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12228. }
  12229. offset += vertexDeclaration[index] * 4;
  12230. }
  12231. }
  12232. }
  12233. this._bindIndexBufferWithCache(indexBuffer);
  12234. };
  12235. Engine.prototype._unbindVertexArrayObject = function () {
  12236. if (!this._cachedVertexArrayObject) {
  12237. return;
  12238. }
  12239. this._cachedVertexArrayObject = null;
  12240. this._gl.bindVertexArray(null);
  12241. };
  12242. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12243. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12244. this._cachedVertexBuffers = vertexBuffers;
  12245. this._cachedEffectForVertexBuffers = effect;
  12246. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12247. }
  12248. this._bindIndexBufferWithCache(indexBuffer);
  12249. };
  12250. Engine.prototype.unbindInstanceAttributes = function () {
  12251. var boundBuffer;
  12252. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12253. var instancesBuffer = this._currentInstanceBuffers[i];
  12254. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12255. boundBuffer = instancesBuffer;
  12256. this.bindArrayBuffer(instancesBuffer);
  12257. }
  12258. var offsetLocation = this._currentInstanceLocations[i];
  12259. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12260. }
  12261. this._currentInstanceBuffers.length = 0;
  12262. this._currentInstanceLocations.length = 0;
  12263. };
  12264. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12265. this._gl.deleteVertexArray(vao);
  12266. };
  12267. Engine.prototype._releaseBuffer = function (buffer) {
  12268. buffer.references--;
  12269. if (buffer.references === 0) {
  12270. this._gl.deleteBuffer(buffer);
  12271. return true;
  12272. }
  12273. return false;
  12274. };
  12275. Engine.prototype.createInstancesBuffer = function (capacity) {
  12276. var buffer = this._gl.createBuffer();
  12277. if (!buffer) {
  12278. throw new Error("Unable to create instance buffer");
  12279. }
  12280. buffer.capacity = capacity;
  12281. this.bindArrayBuffer(buffer);
  12282. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12283. return buffer;
  12284. };
  12285. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12286. this._gl.deleteBuffer(buffer);
  12287. };
  12288. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12289. this.bindArrayBuffer(instancesBuffer);
  12290. if (data) {
  12291. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12292. }
  12293. if (offsetLocations[0].index !== undefined) {
  12294. var stride = 0;
  12295. for (var i = 0; i < offsetLocations.length; i++) {
  12296. var ai = offsetLocations[i];
  12297. stride += ai.attributeSize * 4;
  12298. }
  12299. for (var i = 0; i < offsetLocations.length; i++) {
  12300. var ai = offsetLocations[i];
  12301. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12302. this._gl.enableVertexAttribArray(ai.index);
  12303. this._vertexAttribArraysEnabled[ai.index] = true;
  12304. }
  12305. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12306. this._gl.vertexAttribDivisor(ai.index, 1);
  12307. this._currentInstanceLocations.push(ai.index);
  12308. this._currentInstanceBuffers.push(instancesBuffer);
  12309. }
  12310. }
  12311. else {
  12312. for (var index = 0; index < 4; index++) {
  12313. var offsetLocation = offsetLocations[index];
  12314. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12315. this._gl.enableVertexAttribArray(offsetLocation);
  12316. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12317. }
  12318. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12319. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12320. this._currentInstanceLocations.push(offsetLocation);
  12321. this._currentInstanceBuffers.push(instancesBuffer);
  12322. }
  12323. }
  12324. };
  12325. Engine.prototype.applyStates = function () {
  12326. this._depthCullingState.apply(this._gl);
  12327. this._stencilState.apply(this._gl);
  12328. this._alphaState.apply(this._gl);
  12329. };
  12330. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12331. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12332. };
  12333. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12334. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12335. };
  12336. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12337. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12338. };
  12339. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12340. // Apply states
  12341. this.applyStates();
  12342. this._drawCalls.addCount(1, false);
  12343. // Render
  12344. var drawMode = this.DrawMode(fillMode);
  12345. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12346. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12347. if (instancesCount) {
  12348. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12349. }
  12350. else {
  12351. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12352. }
  12353. };
  12354. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12355. // Apply states
  12356. this.applyStates();
  12357. this._drawCalls.addCount(1, false);
  12358. var drawMode = this.DrawMode(fillMode);
  12359. if (instancesCount) {
  12360. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12361. }
  12362. else {
  12363. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12364. }
  12365. };
  12366. Engine.prototype.DrawMode = function (fillMode) {
  12367. switch (fillMode) {
  12368. // Triangle views
  12369. case BABYLON.Material.TriangleFillMode:
  12370. return this._gl.TRIANGLES;
  12371. case BABYLON.Material.PointFillMode:
  12372. return this._gl.POINTS;
  12373. case BABYLON.Material.WireFrameFillMode:
  12374. return this._gl.LINES;
  12375. // Draw modes
  12376. case BABYLON.Material.PointListDrawMode:
  12377. return this._gl.POINTS;
  12378. case BABYLON.Material.LineListDrawMode:
  12379. return this._gl.LINES;
  12380. case BABYLON.Material.LineLoopDrawMode:
  12381. return this._gl.LINE_LOOP;
  12382. case BABYLON.Material.LineStripDrawMode:
  12383. return this._gl.LINE_STRIP;
  12384. case BABYLON.Material.TriangleStripDrawMode:
  12385. return this._gl.TRIANGLE_STRIP;
  12386. case BABYLON.Material.TriangleFanDrawMode:
  12387. return this._gl.TRIANGLE_FAN;
  12388. default:
  12389. return this._gl.TRIANGLES;
  12390. }
  12391. };
  12392. // Shaders
  12393. Engine.prototype._releaseEffect = function (effect) {
  12394. if (this._compiledEffects[effect._key]) {
  12395. delete this._compiledEffects[effect._key];
  12396. this._deleteProgram(effect.getProgram());
  12397. }
  12398. };
  12399. Engine.prototype._deleteProgram = function (program) {
  12400. if (program) {
  12401. program.__SPECTOR_rebuildProgram = null;
  12402. if (program.transformFeedback) {
  12403. this.deleteTransformFeedback(program.transformFeedback);
  12404. program.transformFeedback = null;
  12405. }
  12406. this._gl.deleteProgram(program);
  12407. }
  12408. };
  12409. /**
  12410. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12411. * @param samplers An array of string used to represent textures
  12412. */
  12413. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12414. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12415. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12416. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12417. if (this._compiledEffects[name]) {
  12418. var compiledEffect = this._compiledEffects[name];
  12419. if (onCompiled && compiledEffect.isReady()) {
  12420. onCompiled(compiledEffect);
  12421. }
  12422. return compiledEffect;
  12423. }
  12424. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12425. effect._key = name;
  12426. this._compiledEffects[name] = effect;
  12427. return effect;
  12428. };
  12429. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12430. if (uniformsNames === void 0) { uniformsNames = []; }
  12431. if (samplers === void 0) { samplers = []; }
  12432. if (defines === void 0) { defines = ""; }
  12433. return this.createEffect({
  12434. vertex: "particles",
  12435. fragmentElement: fragmentName
  12436. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12437. };
  12438. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12439. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12440. context = context || this._gl;
  12441. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12442. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12443. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12444. };
  12445. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12446. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12447. context = context || this._gl;
  12448. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12449. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12450. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12451. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12452. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12453. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12454. return program;
  12455. };
  12456. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12457. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12458. var shaderProgram = context.createProgram();
  12459. if (!shaderProgram) {
  12460. throw new Error("Unable to create program");
  12461. }
  12462. context.attachShader(shaderProgram, vertexShader);
  12463. context.attachShader(shaderProgram, fragmentShader);
  12464. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12465. var transformFeedback = this.createTransformFeedback();
  12466. this.bindTransformFeedback(transformFeedback);
  12467. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12468. shaderProgram.transformFeedback = transformFeedback;
  12469. }
  12470. context.linkProgram(shaderProgram);
  12471. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12472. this.bindTransformFeedback(null);
  12473. }
  12474. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12475. if (!linked) {
  12476. context.validateProgram(shaderProgram);
  12477. var error = context.getProgramInfoLog(shaderProgram);
  12478. if (error) {
  12479. throw new Error(error);
  12480. }
  12481. }
  12482. context.deleteShader(vertexShader);
  12483. context.deleteShader(fragmentShader);
  12484. return shaderProgram;
  12485. };
  12486. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12487. var results = new Array();
  12488. for (var index = 0; index < uniformsNames.length; index++) {
  12489. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12490. }
  12491. return results;
  12492. };
  12493. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12494. var results = [];
  12495. for (var index = 0; index < attributesNames.length; index++) {
  12496. try {
  12497. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12498. }
  12499. catch (e) {
  12500. results.push(-1);
  12501. }
  12502. }
  12503. return results;
  12504. };
  12505. Engine.prototype.enableEffect = function (effect) {
  12506. if (!effect) {
  12507. return;
  12508. }
  12509. // Use program
  12510. this.bindSamplers(effect);
  12511. this._currentEffect = effect;
  12512. if (effect.onBind) {
  12513. effect.onBind(effect);
  12514. }
  12515. effect.onBindObservable.notifyObservers(effect);
  12516. };
  12517. Engine.prototype.setIntArray = function (uniform, array) {
  12518. if (!uniform)
  12519. return;
  12520. this._gl.uniform1iv(uniform, array);
  12521. };
  12522. Engine.prototype.setIntArray2 = function (uniform, array) {
  12523. if (!uniform || array.length % 2 !== 0)
  12524. return;
  12525. this._gl.uniform2iv(uniform, array);
  12526. };
  12527. Engine.prototype.setIntArray3 = function (uniform, array) {
  12528. if (!uniform || array.length % 3 !== 0)
  12529. return;
  12530. this._gl.uniform3iv(uniform, array);
  12531. };
  12532. Engine.prototype.setIntArray4 = function (uniform, array) {
  12533. if (!uniform || array.length % 4 !== 0)
  12534. return;
  12535. this._gl.uniform4iv(uniform, array);
  12536. };
  12537. Engine.prototype.setFloatArray = function (uniform, array) {
  12538. if (!uniform)
  12539. return;
  12540. this._gl.uniform1fv(uniform, array);
  12541. };
  12542. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12543. if (!uniform || array.length % 2 !== 0)
  12544. return;
  12545. this._gl.uniform2fv(uniform, array);
  12546. };
  12547. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12548. if (!uniform || array.length % 3 !== 0)
  12549. return;
  12550. this._gl.uniform3fv(uniform, array);
  12551. };
  12552. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12553. if (!uniform || array.length % 4 !== 0)
  12554. return;
  12555. this._gl.uniform4fv(uniform, array);
  12556. };
  12557. Engine.prototype.setArray = function (uniform, array) {
  12558. if (!uniform)
  12559. return;
  12560. this._gl.uniform1fv(uniform, array);
  12561. };
  12562. Engine.prototype.setArray2 = function (uniform, array) {
  12563. if (!uniform || array.length % 2 !== 0)
  12564. return;
  12565. this._gl.uniform2fv(uniform, array);
  12566. };
  12567. Engine.prototype.setArray3 = function (uniform, array) {
  12568. if (!uniform || array.length % 3 !== 0)
  12569. return;
  12570. this._gl.uniform3fv(uniform, array);
  12571. };
  12572. Engine.prototype.setArray4 = function (uniform, array) {
  12573. if (!uniform || array.length % 4 !== 0)
  12574. return;
  12575. this._gl.uniform4fv(uniform, array);
  12576. };
  12577. Engine.prototype.setMatrices = function (uniform, matrices) {
  12578. if (!uniform)
  12579. return;
  12580. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12581. };
  12582. Engine.prototype.setMatrix = function (uniform, matrix) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12586. };
  12587. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12588. if (!uniform)
  12589. return;
  12590. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12591. };
  12592. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12593. if (!uniform)
  12594. return;
  12595. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12596. };
  12597. Engine.prototype.setInt = function (uniform, value) {
  12598. if (!uniform)
  12599. return;
  12600. this._gl.uniform1i(uniform, value);
  12601. };
  12602. Engine.prototype.setFloat = function (uniform, value) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniform1f(uniform, value);
  12606. };
  12607. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniform2f(uniform, x, y);
  12611. };
  12612. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniform3f(uniform, x, y, z);
  12616. };
  12617. Engine.prototype.setBool = function (uniform, bool) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniform1i(uniform, bool);
  12621. };
  12622. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform4f(uniform, x, y, z, w);
  12626. };
  12627. Engine.prototype.setColor3 = function (uniform, color3) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12631. };
  12632. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12633. if (!uniform)
  12634. return;
  12635. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12636. };
  12637. /**
  12638. * Sets a Color4 on a uniform variable
  12639. * @param uniform defines the uniform location
  12640. * @param color4 defines the value to be set
  12641. */
  12642. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12646. };
  12647. // States
  12648. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12649. if (zOffset === void 0) { zOffset = 0; }
  12650. if (reverseSide === void 0) { reverseSide = false; }
  12651. // Culling
  12652. if (this._depthCullingState.cull !== culling || force) {
  12653. this._depthCullingState.cull = culling;
  12654. }
  12655. // Cull face
  12656. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12657. if (this._depthCullingState.cullFace !== cullFace || force) {
  12658. this._depthCullingState.cullFace = cullFace;
  12659. }
  12660. // Z offset
  12661. this.setZOffset(zOffset);
  12662. // Front face
  12663. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12664. if (this._depthCullingState.frontFace !== frontFace || force) {
  12665. this._depthCullingState.frontFace = frontFace;
  12666. }
  12667. };
  12668. Engine.prototype.setZOffset = function (value) {
  12669. this._depthCullingState.zOffset = value;
  12670. };
  12671. Engine.prototype.getZOffset = function () {
  12672. return this._depthCullingState.zOffset;
  12673. };
  12674. Engine.prototype.setDepthBuffer = function (enable) {
  12675. this._depthCullingState.depthTest = enable;
  12676. };
  12677. Engine.prototype.getDepthWrite = function () {
  12678. return this._depthCullingState.depthMask;
  12679. };
  12680. Engine.prototype.setDepthWrite = function (enable) {
  12681. this._depthCullingState.depthMask = enable;
  12682. };
  12683. Engine.prototype.setColorWrite = function (enable) {
  12684. this._gl.colorMask(enable, enable, enable, enable);
  12685. this._colorWrite = enable;
  12686. };
  12687. Engine.prototype.getColorWrite = function () {
  12688. return this._colorWrite;
  12689. };
  12690. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12691. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12692. };
  12693. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12694. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12695. if (this._alphaMode === mode) {
  12696. return;
  12697. }
  12698. switch (mode) {
  12699. case Engine.ALPHA_DISABLE:
  12700. this._alphaState.alphaBlend = false;
  12701. break;
  12702. case Engine.ALPHA_PREMULTIPLIED:
  12703. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12704. this._alphaState.alphaBlend = true;
  12705. break;
  12706. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12707. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12708. this._alphaState.alphaBlend = true;
  12709. break;
  12710. case Engine.ALPHA_COMBINE:
  12711. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12712. this._alphaState.alphaBlend = true;
  12713. break;
  12714. case Engine.ALPHA_ONEONE:
  12715. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12716. this._alphaState.alphaBlend = true;
  12717. break;
  12718. case Engine.ALPHA_ADD:
  12719. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12720. this._alphaState.alphaBlend = true;
  12721. break;
  12722. case Engine.ALPHA_SUBTRACT:
  12723. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12724. this._alphaState.alphaBlend = true;
  12725. break;
  12726. case Engine.ALPHA_MULTIPLY:
  12727. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12728. this._alphaState.alphaBlend = true;
  12729. break;
  12730. case Engine.ALPHA_MAXIMIZED:
  12731. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12732. this._alphaState.alphaBlend = true;
  12733. break;
  12734. case Engine.ALPHA_INTERPOLATE:
  12735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12736. this._alphaState.alphaBlend = true;
  12737. break;
  12738. case Engine.ALPHA_SCREENMODE:
  12739. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12740. this._alphaState.alphaBlend = true;
  12741. break;
  12742. }
  12743. if (!noDepthWriteChange) {
  12744. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12745. }
  12746. this._alphaMode = mode;
  12747. };
  12748. Engine.prototype.getAlphaMode = function () {
  12749. return this._alphaMode;
  12750. };
  12751. // Textures
  12752. Engine.prototype.wipeCaches = function (bruteForce) {
  12753. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12754. return;
  12755. }
  12756. this._currentEffect = null;
  12757. // 6/8/2017: deltakosh: Should not be required anymore.
  12758. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12759. if (bruteForce) {
  12760. this.resetTextureCache();
  12761. this._currentProgram = null;
  12762. this._stencilState.reset();
  12763. this._depthCullingState.reset();
  12764. this.setDepthFunctionToLessOrEqual();
  12765. this._alphaState.reset();
  12766. }
  12767. this._resetVertexBufferBinding();
  12768. this._cachedIndexBuffer = null;
  12769. this._cachedEffectForVertexBuffers = null;
  12770. this._unbindVertexArrayObject();
  12771. this.bindIndexBuffer(null);
  12772. };
  12773. /**
  12774. * Set the compressed texture format to use, based on the formats you have, and the formats
  12775. * supported by the hardware / browser.
  12776. *
  12777. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12778. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12779. * to API arguments needed to compressed textures. This puts the burden on the container
  12780. * generator to house the arcane code for determining these for current & future formats.
  12781. *
  12782. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12783. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12784. *
  12785. * Note: The result of this call is not taken into account when a texture is base64.
  12786. *
  12787. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12788. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12789. *
  12790. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12791. * @returns The extension selected.
  12792. */
  12793. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12794. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12795. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12796. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12797. return this._textureFormatInUse = this._texturesSupported[i];
  12798. }
  12799. }
  12800. }
  12801. // actively set format to nothing, to allow this to be called more than once
  12802. // and possibly fail the 2nd time
  12803. this._textureFormatInUse = null;
  12804. return null;
  12805. };
  12806. Engine.prototype._createTexture = function () {
  12807. var texture = this._gl.createTexture();
  12808. if (!texture) {
  12809. throw new Error("Unable to create texture");
  12810. }
  12811. return texture;
  12812. };
  12813. /**
  12814. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12815. * @param {string} urlArg- This contains one of the following:
  12816. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12817. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12818. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12819. *
  12820. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12821. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12822. * @param {Scene} scene- Needed for loading to the correct scene.
  12823. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12824. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12825. * @param {callback} onError- Optional callback to be called upon failure.
  12826. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12827. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12828. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12829. *
  12830. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12831. */
  12832. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12833. var _this = this;
  12834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12835. if (onLoad === void 0) { onLoad = null; }
  12836. if (onError === void 0) { onError = null; }
  12837. if (buffer === void 0) { buffer = null; }
  12838. if (fallBack === void 0) { fallBack = null; }
  12839. if (format === void 0) { format = null; }
  12840. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12841. var fromData = url.substr(0, 5) === "data:";
  12842. var fromBlob = url.substr(0, 5) === "blob:";
  12843. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12844. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12845. // establish the file extension, if possible
  12846. var lastDot = url.lastIndexOf('.');
  12847. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12848. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12849. var isTGA = (extension.indexOf(".tga") === 0);
  12850. // determine if a ktx file should be substituted
  12851. var isKTX = false;
  12852. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12853. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12854. isKTX = true;
  12855. }
  12856. if (scene) {
  12857. scene._addPendingData(texture);
  12858. }
  12859. texture.url = url;
  12860. texture.generateMipMaps = !noMipmap;
  12861. texture.samplingMode = samplingMode;
  12862. texture.invertY = invertY;
  12863. if (!this._doNotHandleContextLost) {
  12864. // Keep a link to the buffer only if we plan to handle context lost
  12865. texture._buffer = buffer;
  12866. }
  12867. var onLoadObserver = null;
  12868. if (onLoad && !fallBack) {
  12869. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12870. }
  12871. if (!fallBack)
  12872. this._internalTexturesCache.push(texture);
  12873. var onerror = function (message, exception) {
  12874. if (scene) {
  12875. scene._removePendingData(texture);
  12876. }
  12877. if (onLoadObserver) {
  12878. texture.onLoadedObservable.remove(onLoadObserver);
  12879. }
  12880. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12881. if (isKTX) {
  12882. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12883. }
  12884. else if (BABYLON.Tools.UseFallbackTexture) {
  12885. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12886. }
  12887. if (onError) {
  12888. onError(message || "Unknown error", exception);
  12889. }
  12890. };
  12891. var callback = null;
  12892. // processing for non-image formats
  12893. if (isKTX || isTGA || isDDS) {
  12894. if (isKTX) {
  12895. callback = function (data) {
  12896. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12897. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12898. ktx.uploadLevels(_this._gl, !noMipmap);
  12899. return false;
  12900. }, samplingMode);
  12901. };
  12902. }
  12903. else if (isTGA) {
  12904. callback = function (arrayBuffer) {
  12905. var data = new Uint8Array(arrayBuffer);
  12906. var header = BABYLON.TGATools.GetTGAHeader(data);
  12907. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12908. BABYLON.TGATools.UploadContent(_this._gl, data);
  12909. return false;
  12910. }, samplingMode);
  12911. };
  12912. }
  12913. else if (isDDS) {
  12914. callback = function (data) {
  12915. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12916. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12917. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12918. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12919. return false;
  12920. }, samplingMode);
  12921. };
  12922. }
  12923. if (!buffer) {
  12924. this._loadFile(url, function (data) {
  12925. if (callback) {
  12926. callback(data);
  12927. }
  12928. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12929. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12930. });
  12931. }
  12932. else {
  12933. if (callback) {
  12934. callback(buffer);
  12935. }
  12936. }
  12937. // image format processing
  12938. }
  12939. else {
  12940. var onload = function (img) {
  12941. if (fromBlob && !_this._doNotHandleContextLost) {
  12942. // We need to store the image if we need to rebuild the texture
  12943. // in case of a webgl context lost
  12944. texture._buffer = img;
  12945. }
  12946. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12947. var gl = _this._gl;
  12948. var isPot = (img.width === potWidth && img.height === potHeight);
  12949. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12950. if (isPot) {
  12951. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12952. return false;
  12953. }
  12954. // Using shaders to rescale because canvas.drawImage is lossy
  12955. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12956. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12957. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12959. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12962. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12963. _this._releaseTexture(source);
  12964. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12965. continuationCallback();
  12966. });
  12967. return true;
  12968. }, samplingMode);
  12969. };
  12970. if (!fromData || isBase64)
  12971. if (buffer instanceof HTMLImageElement) {
  12972. onload(buffer);
  12973. }
  12974. else {
  12975. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12976. }
  12977. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12978. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12979. else
  12980. onload(buffer);
  12981. }
  12982. return texture;
  12983. };
  12984. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12985. var _this = this;
  12986. var rtt = this.createRenderTargetTexture({
  12987. width: destination.width,
  12988. height: destination.height,
  12989. }, {
  12990. generateMipMaps: false,
  12991. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12992. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12993. generateDepthBuffer: false,
  12994. generateStencilBuffer: false
  12995. });
  12996. if (!this._rescalePostProcess) {
  12997. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12998. }
  12999. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13000. _this._rescalePostProcess.onApply = function (effect) {
  13001. effect._bindTexture("textureSampler", source);
  13002. };
  13003. var hostingScene = scene;
  13004. if (!hostingScene) {
  13005. hostingScene = _this.scenes[_this.scenes.length - 1];
  13006. }
  13007. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13008. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13009. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13010. _this.unBindFramebuffer(rtt);
  13011. _this._releaseTexture(rtt);
  13012. if (onComplete) {
  13013. onComplete();
  13014. }
  13015. });
  13016. };
  13017. Engine.prototype._getInternalFormat = function (format) {
  13018. var internalFormat = this._gl.RGBA;
  13019. switch (format) {
  13020. case Engine.TEXTUREFORMAT_ALPHA:
  13021. internalFormat = this._gl.ALPHA;
  13022. break;
  13023. case Engine.TEXTUREFORMAT_LUMINANCE:
  13024. internalFormat = this._gl.LUMINANCE;
  13025. break;
  13026. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13027. internalFormat = this._gl.LUMINANCE_ALPHA;
  13028. break;
  13029. case Engine.TEXTUREFORMAT_RGB:
  13030. case Engine.TEXTUREFORMAT_RGB32F:
  13031. internalFormat = this._gl.RGB;
  13032. break;
  13033. case Engine.TEXTUREFORMAT_RGBA:
  13034. case Engine.TEXTUREFORMAT_RGBA32F:
  13035. internalFormat = this._gl.RGBA;
  13036. break;
  13037. case Engine.TEXTUREFORMAT_R32F:
  13038. internalFormat = this._gl.RED;
  13039. break;
  13040. case Engine.TEXTUREFORMAT_RG32F:
  13041. internalFormat = this._gl.RG;
  13042. break;
  13043. }
  13044. return internalFormat;
  13045. };
  13046. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13047. if (compression === void 0) { compression = null; }
  13048. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13049. if (!texture) {
  13050. return;
  13051. }
  13052. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13053. var internalFormat = this._getInternalFormat(format);
  13054. var textureType = this._getWebGLTextureType(type);
  13055. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13056. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13057. if (!this._doNotHandleContextLost) {
  13058. texture._bufferView = data;
  13059. texture.format = format;
  13060. texture.type = type;
  13061. texture.invertY = invertY;
  13062. texture._compression = compression;
  13063. }
  13064. if (texture.width % 4 !== 0) {
  13065. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13066. }
  13067. if (compression && data) {
  13068. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13069. }
  13070. else {
  13071. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13072. }
  13073. if (texture.generateMipMaps) {
  13074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13075. }
  13076. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13077. // this.resetTextureCache();
  13078. texture.isReady = true;
  13079. };
  13080. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13081. if (compression === void 0) { compression = null; }
  13082. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13084. texture.baseWidth = width;
  13085. texture.baseHeight = height;
  13086. texture.width = width;
  13087. texture.height = height;
  13088. texture.format = format;
  13089. texture.generateMipMaps = generateMipMaps;
  13090. texture.samplingMode = samplingMode;
  13091. texture.invertY = invertY;
  13092. texture._compression = compression;
  13093. texture.type = type;
  13094. if (!this._doNotHandleContextLost) {
  13095. texture._bufferView = data;
  13096. }
  13097. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13098. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13099. // Filters
  13100. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13101. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13102. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13103. if (generateMipMaps) {
  13104. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13105. }
  13106. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13107. this._internalTexturesCache.push(texture);
  13108. return texture;
  13109. };
  13110. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13111. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13112. texture.baseWidth = width;
  13113. texture.baseHeight = height;
  13114. if (generateMipMaps) {
  13115. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13116. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13117. }
  13118. // this.resetTextureCache();
  13119. texture.width = width;
  13120. texture.height = height;
  13121. texture.isReady = false;
  13122. texture.generateMipMaps = generateMipMaps;
  13123. texture.samplingMode = samplingMode;
  13124. this.updateTextureSamplingMode(samplingMode, texture);
  13125. this._internalTexturesCache.push(texture);
  13126. return texture;
  13127. };
  13128. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13129. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13130. if (texture.isCube) {
  13131. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13132. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13133. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13134. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13135. }
  13136. else if (texture.is3D) {
  13137. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13138. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13139. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13140. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13141. }
  13142. else {
  13143. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13144. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13145. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13146. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13147. }
  13148. texture.samplingMode = samplingMode;
  13149. };
  13150. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13151. if (premulAlpha === void 0) { premulAlpha = false; }
  13152. if (!texture) {
  13153. return;
  13154. }
  13155. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13156. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13157. if (premulAlpha) {
  13158. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13159. }
  13160. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13161. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13162. if (texture.generateMipMaps) {
  13163. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13164. }
  13165. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13166. if (premulAlpha) {
  13167. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13168. }
  13169. texture.isReady = true;
  13170. };
  13171. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13172. if (!texture || texture._isDisabled) {
  13173. return;
  13174. }
  13175. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13176. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13177. try {
  13178. // Testing video texture support
  13179. if (this._videoTextureSupported === undefined) {
  13180. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13181. if (this._gl.getError() !== 0) {
  13182. this._videoTextureSupported = false;
  13183. }
  13184. else {
  13185. this._videoTextureSupported = true;
  13186. }
  13187. }
  13188. // Copy video through the current working canvas if video texture is not supported
  13189. if (!this._videoTextureSupported) {
  13190. if (!texture._workingCanvas) {
  13191. texture._workingCanvas = document.createElement("canvas");
  13192. var context = texture._workingCanvas.getContext("2d");
  13193. if (!context) {
  13194. throw new Error("Unable to get 2d context");
  13195. }
  13196. texture._workingContext = context;
  13197. texture._workingCanvas.width = texture.width;
  13198. texture._workingCanvas.height = texture.height;
  13199. }
  13200. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13201. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13202. }
  13203. else {
  13204. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13205. }
  13206. if (texture.generateMipMaps) {
  13207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13208. }
  13209. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13210. // this.resetTextureCache();
  13211. texture.isReady = true;
  13212. }
  13213. catch (ex) {
  13214. // Something unexpected
  13215. // Let's disable the texture
  13216. texture._isDisabled = true;
  13217. }
  13218. };
  13219. /**
  13220. * Updates a depth texture Comparison Mode and Function.
  13221. * If the comparison Function is equal to 0, the mode will be set to none.
  13222. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13223. * @param texture The texture to set the comparison function for
  13224. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13225. */
  13226. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13227. if (this.webGLVersion === 1) {
  13228. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13229. return;
  13230. }
  13231. var gl = this._gl;
  13232. if (texture.isCube) {
  13233. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13234. if (comparisonFunction === 0) {
  13235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13237. }
  13238. else {
  13239. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13240. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13241. }
  13242. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13243. }
  13244. else {
  13245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13246. if (comparisonFunction === 0) {
  13247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13249. }
  13250. else {
  13251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13253. }
  13254. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13255. }
  13256. texture._comparisonFunction = comparisonFunction;
  13257. };
  13258. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13259. var width = size.width || size;
  13260. var height = size.height || size;
  13261. internalTexture.baseWidth = width;
  13262. internalTexture.baseHeight = height;
  13263. internalTexture.width = width;
  13264. internalTexture.height = height;
  13265. internalTexture.isReady = true;
  13266. internalTexture.samples = 1;
  13267. internalTexture.generateMipMaps = false;
  13268. internalTexture._generateDepthBuffer = true;
  13269. internalTexture._generateStencilBuffer = generateStencil;
  13270. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13271. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13272. internalTexture._comparisonFunction = comparisonFunction;
  13273. var gl = this._gl;
  13274. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13275. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13276. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13277. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13278. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13279. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13280. if (comparisonFunction === 0) {
  13281. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13282. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13283. }
  13284. else {
  13285. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13286. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13287. }
  13288. };
  13289. /**
  13290. * Creates a depth stencil texture.
  13291. * This is only available in WebGL 2 or with the depth texture extension available.
  13292. * @param size The size of face edge in the texture.
  13293. * @param options The options defining the texture.
  13294. * @returns The texture
  13295. */
  13296. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13297. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13298. if (!this._caps.depthTextureExtension) {
  13299. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13300. return internalTexture;
  13301. }
  13302. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13303. var gl = this._gl;
  13304. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13305. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13306. if (this.webGLVersion > 1) {
  13307. if (internalOptions.generateStencil) {
  13308. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13309. }
  13310. else {
  13311. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13312. }
  13313. }
  13314. else {
  13315. if (internalOptions.generateStencil) {
  13316. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13317. }
  13318. else {
  13319. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13320. }
  13321. }
  13322. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13323. return internalTexture;
  13324. };
  13325. /**
  13326. * Creates a depth stencil cube texture.
  13327. * This is only available in WebGL 2.
  13328. * @param size The size of face edge in the cube texture.
  13329. * @param options The options defining the cube texture.
  13330. * @returns The cube texture
  13331. */
  13332. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13333. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13334. internalTexture.isCube = true;
  13335. if (this.webGLVersion === 1) {
  13336. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13337. return internalTexture;
  13338. }
  13339. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13340. var gl = this._gl;
  13341. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13342. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13343. // Create the depth/stencil buffer
  13344. for (var face = 0; face < 6; face++) {
  13345. if (internalOptions.generateStencil) {
  13346. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13347. }
  13348. else {
  13349. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13350. }
  13351. }
  13352. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13353. return internalTexture;
  13354. };
  13355. /**
  13356. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13357. * @param renderTarget The render target to set the frame buffer for
  13358. */
  13359. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13360. // Create the framebuffer
  13361. var internalTexture = renderTarget.getInternalTexture();
  13362. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13363. return;
  13364. }
  13365. var gl = this._gl;
  13366. var depthStencilTexture = renderTarget.depthStencilTexture;
  13367. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13368. if (depthStencilTexture.isCube) {
  13369. if (depthStencilTexture._generateStencilBuffer) {
  13370. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13371. }
  13372. else {
  13373. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13374. }
  13375. }
  13376. else {
  13377. if (depthStencilTexture._generateStencilBuffer) {
  13378. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13379. }
  13380. else {
  13381. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13382. }
  13383. }
  13384. this.bindUnboundFramebuffer(null);
  13385. };
  13386. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13387. var fullOptions = new RenderTargetCreationOptions();
  13388. if (options !== undefined && typeof options === "object") {
  13389. fullOptions.generateMipMaps = options.generateMipMaps;
  13390. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13391. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13392. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13393. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13394. }
  13395. else {
  13396. fullOptions.generateMipMaps = options;
  13397. fullOptions.generateDepthBuffer = true;
  13398. fullOptions.generateStencilBuffer = false;
  13399. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13400. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13401. }
  13402. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13403. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13404. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13405. }
  13406. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13407. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13408. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13409. }
  13410. var gl = this._gl;
  13411. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13412. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13413. var width = size.width || size;
  13414. var height = size.height || size;
  13415. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13416. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13417. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13418. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13419. }
  13420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13424. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13425. // Create the framebuffer
  13426. var framebuffer = gl.createFramebuffer();
  13427. this.bindUnboundFramebuffer(framebuffer);
  13428. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13429. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13430. if (fullOptions.generateMipMaps) {
  13431. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13432. }
  13433. // Unbind
  13434. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13435. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13436. this.bindUnboundFramebuffer(null);
  13437. texture._framebuffer = framebuffer;
  13438. texture.baseWidth = width;
  13439. texture.baseHeight = height;
  13440. texture.width = width;
  13441. texture.height = height;
  13442. texture.isReady = true;
  13443. texture.samples = 1;
  13444. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13445. texture.samplingMode = fullOptions.samplingMode;
  13446. texture.type = fullOptions.type;
  13447. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13448. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13449. // this.resetTextureCache();
  13450. this._internalTexturesCache.push(texture);
  13451. return texture;
  13452. };
  13453. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13454. var generateMipMaps = false;
  13455. var generateDepthBuffer = true;
  13456. var generateStencilBuffer = false;
  13457. var generateDepthTexture = false;
  13458. var textureCount = 1;
  13459. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13460. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13461. var types = [], samplingModes = [];
  13462. if (options !== undefined) {
  13463. generateMipMaps = options.generateMipMaps;
  13464. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13465. generateStencilBuffer = options.generateStencilBuffer;
  13466. generateDepthTexture = options.generateDepthTexture;
  13467. textureCount = options.textureCount || 1;
  13468. if (options.types) {
  13469. types = options.types;
  13470. }
  13471. if (options.samplingModes) {
  13472. samplingModes = options.samplingModes;
  13473. }
  13474. }
  13475. var gl = this._gl;
  13476. // Create the framebuffer
  13477. var framebuffer = gl.createFramebuffer();
  13478. this.bindUnboundFramebuffer(framebuffer);
  13479. var width = size.width || size;
  13480. var height = size.height || size;
  13481. var textures = [];
  13482. var attachments = [];
  13483. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13484. for (var i = 0; i < textureCount; i++) {
  13485. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13486. var type = types[i] || defaultType;
  13487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13488. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13490. }
  13491. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13492. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13493. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13494. }
  13495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13496. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13497. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13498. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13499. }
  13500. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13501. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13502. textures.push(texture);
  13503. attachments.push(attachment);
  13504. gl.activeTexture(gl["TEXTURE" + i]);
  13505. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13510. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13511. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13512. if (generateMipMaps) {
  13513. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13514. }
  13515. // Unbind
  13516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13517. texture._framebuffer = framebuffer;
  13518. texture._depthStencilBuffer = depthStencilBuffer;
  13519. texture.baseWidth = width;
  13520. texture.baseHeight = height;
  13521. texture.width = width;
  13522. texture.height = height;
  13523. texture.isReady = true;
  13524. texture.samples = 1;
  13525. texture.generateMipMaps = generateMipMaps;
  13526. texture.samplingMode = samplingMode;
  13527. texture.type = type;
  13528. texture._generateDepthBuffer = generateDepthBuffer;
  13529. texture._generateStencilBuffer = generateStencilBuffer;
  13530. texture._attachments = attachments;
  13531. this._internalTexturesCache.push(texture);
  13532. }
  13533. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13534. // Depth texture
  13535. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13536. gl.activeTexture(gl.TEXTURE0);
  13537. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13542. 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);
  13543. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13544. depthTexture._framebuffer = framebuffer;
  13545. depthTexture.baseWidth = width;
  13546. depthTexture.baseHeight = height;
  13547. depthTexture.width = width;
  13548. depthTexture.height = height;
  13549. depthTexture.isReady = true;
  13550. depthTexture.samples = 1;
  13551. depthTexture.generateMipMaps = generateMipMaps;
  13552. depthTexture.samplingMode = gl.NEAREST;
  13553. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13554. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13555. textures.push(depthTexture);
  13556. this._internalTexturesCache.push(depthTexture);
  13557. }
  13558. gl.drawBuffers(attachments);
  13559. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13560. this.bindUnboundFramebuffer(null);
  13561. this.resetTextureCache();
  13562. return textures;
  13563. };
  13564. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13565. if (samples === void 0) { samples = 1; }
  13566. var depthStencilBuffer = null;
  13567. var gl = this._gl;
  13568. // Create the depth/stencil buffer
  13569. if (generateStencilBuffer) {
  13570. depthStencilBuffer = gl.createRenderbuffer();
  13571. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13572. if (samples > 1) {
  13573. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13574. }
  13575. else {
  13576. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13577. }
  13578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13579. }
  13580. else if (generateDepthBuffer) {
  13581. depthStencilBuffer = gl.createRenderbuffer();
  13582. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13583. if (samples > 1) {
  13584. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13585. }
  13586. else {
  13587. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13588. }
  13589. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13590. }
  13591. return depthStencilBuffer;
  13592. };
  13593. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13594. if (this.webGLVersion < 2 || !texture) {
  13595. return 1;
  13596. }
  13597. if (texture.samples === samples) {
  13598. return samples;
  13599. }
  13600. var gl = this._gl;
  13601. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13602. // Dispose previous render buffers
  13603. if (texture._depthStencilBuffer) {
  13604. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13605. texture._depthStencilBuffer = null;
  13606. }
  13607. if (texture._MSAAFramebuffer) {
  13608. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13609. texture._MSAAFramebuffer = null;
  13610. }
  13611. if (texture._MSAARenderBuffer) {
  13612. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13613. texture._MSAARenderBuffer = null;
  13614. }
  13615. if (samples > 1) {
  13616. var framebuffer = gl.createFramebuffer();
  13617. if (!framebuffer) {
  13618. throw new Error("Unable to create multi sampled framebuffer");
  13619. }
  13620. texture._MSAAFramebuffer = framebuffer;
  13621. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13622. var colorRenderbuffer = gl.createRenderbuffer();
  13623. if (!colorRenderbuffer) {
  13624. throw new Error("Unable to create multi sampled framebuffer");
  13625. }
  13626. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13627. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13628. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13629. texture._MSAARenderBuffer = colorRenderbuffer;
  13630. }
  13631. else {
  13632. this.bindUnboundFramebuffer(texture._framebuffer);
  13633. }
  13634. texture.samples = samples;
  13635. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13636. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13637. this.bindUnboundFramebuffer(null);
  13638. return samples;
  13639. };
  13640. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13641. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13642. return 1;
  13643. }
  13644. if (textures[0].samples === samples) {
  13645. return samples;
  13646. }
  13647. var gl = this._gl;
  13648. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13649. // Dispose previous render buffers
  13650. if (textures[0]._depthStencilBuffer) {
  13651. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13652. textures[0]._depthStencilBuffer = null;
  13653. }
  13654. if (textures[0]._MSAAFramebuffer) {
  13655. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13656. textures[0]._MSAAFramebuffer = null;
  13657. }
  13658. for (var i = 0; i < textures.length; i++) {
  13659. if (textures[i]._MSAARenderBuffer) {
  13660. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13661. textures[i]._MSAARenderBuffer = null;
  13662. }
  13663. }
  13664. if (samples > 1) {
  13665. var framebuffer = gl.createFramebuffer();
  13666. if (!framebuffer) {
  13667. throw new Error("Unable to create multi sampled framebuffer");
  13668. }
  13669. this.bindUnboundFramebuffer(framebuffer);
  13670. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13671. var attachments = [];
  13672. for (var i = 0; i < textures.length; i++) {
  13673. var texture = textures[i];
  13674. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13675. var colorRenderbuffer = gl.createRenderbuffer();
  13676. if (!colorRenderbuffer) {
  13677. throw new Error("Unable to create multi sampled framebuffer");
  13678. }
  13679. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13680. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13682. texture._MSAAFramebuffer = framebuffer;
  13683. texture._MSAARenderBuffer = colorRenderbuffer;
  13684. texture.samples = samples;
  13685. texture._depthStencilBuffer = depthStencilBuffer;
  13686. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13687. attachments.push(attachment);
  13688. }
  13689. gl.drawBuffers(attachments);
  13690. }
  13691. else {
  13692. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13693. }
  13694. this.bindUnboundFramebuffer(null);
  13695. return samples;
  13696. };
  13697. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13698. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13699. };
  13700. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13701. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13702. };
  13703. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13704. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13705. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13706. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13707. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13708. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13709. }
  13710. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13711. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13712. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13713. }
  13714. var gl = this._gl;
  13715. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13717. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13718. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13719. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13720. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13721. }
  13722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13726. for (var face = 0; face < 6; face++) {
  13727. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13728. }
  13729. // Create the framebuffer
  13730. var framebuffer = gl.createFramebuffer();
  13731. this.bindUnboundFramebuffer(framebuffer);
  13732. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13733. // MipMaps
  13734. if (fullOptions.generateMipMaps) {
  13735. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13736. }
  13737. // Unbind
  13738. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13739. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13740. this.bindUnboundFramebuffer(null);
  13741. texture._framebuffer = framebuffer;
  13742. texture.width = size;
  13743. texture.height = size;
  13744. texture.isReady = true;
  13745. texture.isCube = true;
  13746. texture.samples = 1;
  13747. texture.generateMipMaps = fullOptions.generateMipMaps;
  13748. texture.samplingMode = fullOptions.samplingMode;
  13749. texture.type = fullOptions.type;
  13750. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13751. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13752. this._internalTexturesCache.push(texture);
  13753. return texture;
  13754. };
  13755. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13756. var _this = this;
  13757. if (onLoad === void 0) { onLoad = null; }
  13758. if (onError === void 0) { onError = null; }
  13759. if (forcedExtension === void 0) { forcedExtension = null; }
  13760. var callback = function (loadData) {
  13761. if (!loadData) {
  13762. if (onLoad) {
  13763. onLoad(null);
  13764. }
  13765. return;
  13766. }
  13767. var texture = loadData.texture;
  13768. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13769. texture._lodGenerationScale = scale;
  13770. texture._lodGenerationOffset = offset;
  13771. if (_this._caps.textureLOD) {
  13772. // Do not add extra process if texture lod is supported.
  13773. if (onLoad) {
  13774. onLoad(texture);
  13775. }
  13776. return;
  13777. }
  13778. var mipSlices = 3;
  13779. var gl = _this._gl;
  13780. var width = loadData.width;
  13781. if (!width) {
  13782. return;
  13783. }
  13784. var textures = [];
  13785. for (var i = 0; i < mipSlices; i++) {
  13786. //compute LOD from even spacing in smoothness (matching shader calculation)
  13787. var smoothness = i / (mipSlices - 1);
  13788. var roughness = 1 - smoothness;
  13789. var minLODIndex = offset; // roughness = 0
  13790. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13791. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13792. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13793. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13794. glTextureFromLod.isCube = true;
  13795. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13800. if (loadData.isDDS) {
  13801. var info = loadData.info;
  13802. var data = loadData.data;
  13803. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13804. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13805. }
  13806. else {
  13807. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13808. }
  13809. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13810. // Wrap in a base texture for easy binding.
  13811. var lodTexture = new BABYLON.BaseTexture(scene);
  13812. lodTexture.isCube = true;
  13813. lodTexture._texture = glTextureFromLod;
  13814. glTextureFromLod.isReady = true;
  13815. textures.push(lodTexture);
  13816. }
  13817. texture._lodTextureHigh = textures[2];
  13818. texture._lodTextureMid = textures[1];
  13819. texture._lodTextureLow = textures[0];
  13820. if (onLoad) {
  13821. onLoad(texture);
  13822. }
  13823. };
  13824. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13825. };
  13826. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13827. var _this = this;
  13828. if (onLoad === void 0) { onLoad = null; }
  13829. if (onError === void 0) { onError = null; }
  13830. if (forcedExtension === void 0) { forcedExtension = null; }
  13831. var gl = this._gl;
  13832. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13833. texture.isCube = true;
  13834. texture.url = rootUrl;
  13835. texture.generateMipMaps = !noMipmap;
  13836. if (!this._doNotHandleContextLost) {
  13837. texture._extension = forcedExtension;
  13838. texture._files = files;
  13839. }
  13840. var isKTX = false;
  13841. var isDDS = false;
  13842. var lastDot = rootUrl.lastIndexOf('.');
  13843. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13844. if (this._textureFormatInUse) {
  13845. extension = this._textureFormatInUse;
  13846. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13847. isKTX = true;
  13848. }
  13849. else {
  13850. isDDS = (extension === ".dds");
  13851. }
  13852. var onerror = function (request, exception) {
  13853. if (onError && request) {
  13854. onError(request.status + " " + request.statusText, exception);
  13855. }
  13856. };
  13857. if (isKTX) {
  13858. this._loadFile(rootUrl, function (data) {
  13859. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13860. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13861. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13862. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13863. ktx.uploadLevels(_this._gl, !noMipmap);
  13864. _this.setCubeMapTextureParams(gl, loadMipmap);
  13865. texture.width = ktx.pixelWidth;
  13866. texture.height = ktx.pixelHeight;
  13867. texture.isReady = true;
  13868. }, undefined, undefined, true, onerror);
  13869. }
  13870. else if (isDDS) {
  13871. if (files && files.length === 6) {
  13872. this._cascadeLoadFiles(scene, function (imgs) {
  13873. var info;
  13874. var loadMipmap = false;
  13875. var width = 0;
  13876. for (var index = 0; index < imgs.length; index++) {
  13877. var data = imgs[index];
  13878. info = BABYLON.DDSTools.GetDDSInfo(data);
  13879. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13880. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13881. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13882. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13883. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13884. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13885. }
  13886. texture.width = info.width;
  13887. texture.height = info.height;
  13888. texture.type = info.textureType;
  13889. width = info.width;
  13890. }
  13891. _this.setCubeMapTextureParams(gl, loadMipmap);
  13892. texture.isReady = true;
  13893. if (onLoad) {
  13894. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13895. }
  13896. }, files, onError);
  13897. }
  13898. else {
  13899. this._loadFile(rootUrl, function (data) {
  13900. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13901. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13902. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13903. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13904. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13905. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13906. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13907. }
  13908. _this.setCubeMapTextureParams(gl, loadMipmap);
  13909. texture.width = info.width;
  13910. texture.height = info.height;
  13911. texture.isReady = true;
  13912. texture.type = info.textureType;
  13913. if (onLoad) {
  13914. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13915. }
  13916. }, undefined, undefined, true, onerror);
  13917. }
  13918. }
  13919. else {
  13920. if (!files) {
  13921. throw new Error("Cannot load cubemap because files were not defined");
  13922. }
  13923. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13924. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13925. var height = width;
  13926. _this._prepareWorkingCanvas();
  13927. if (!_this._workingCanvas || !_this._workingContext) {
  13928. return;
  13929. }
  13930. _this._workingCanvas.width = width;
  13931. _this._workingCanvas.height = height;
  13932. var faces = [
  13933. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13934. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13935. ];
  13936. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13937. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13938. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13939. for (var index = 0; index < faces.length; index++) {
  13940. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13941. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13942. }
  13943. if (!noMipmap) {
  13944. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13945. }
  13946. _this.setCubeMapTextureParams(gl, !noMipmap);
  13947. texture.width = width;
  13948. texture.height = height;
  13949. texture.isReady = true;
  13950. if (format) {
  13951. texture.format = format;
  13952. }
  13953. texture.onLoadedObservable.notifyObservers(texture);
  13954. texture.onLoadedObservable.clear();
  13955. if (onLoad) {
  13956. onLoad();
  13957. }
  13958. }, files, onError);
  13959. }
  13960. this._internalTexturesCache.push(texture);
  13961. return texture;
  13962. };
  13963. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13968. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13969. // this.resetTextureCache();
  13970. };
  13971. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13972. if (compression === void 0) { compression = null; }
  13973. if (level === void 0) { level = 0; }
  13974. texture._bufferViewArray = data;
  13975. texture.format = format;
  13976. texture.type = type;
  13977. texture.invertY = invertY;
  13978. texture._compression = compression;
  13979. var gl = this._gl;
  13980. var textureType = this._getWebGLTextureType(type);
  13981. var internalFormat = this._getInternalFormat(format);
  13982. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13983. var needConversion = false;
  13984. if (internalFormat === gl.RGB) {
  13985. internalFormat = gl.RGBA;
  13986. needConversion = true;
  13987. }
  13988. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13989. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13990. if (texture.width % 4 !== 0) {
  13991. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13992. }
  13993. // Data are known to be in +X +Y +Z -X -Y -Z
  13994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13995. var faceData = data[faceIndex];
  13996. if (compression) {
  13997. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13998. }
  13999. else {
  14000. if (needConversion) {
  14001. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14002. }
  14003. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14004. }
  14005. }
  14006. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14007. if (isPot && texture.generateMipMaps && level === 0) {
  14008. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14009. }
  14010. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14011. // this.resetTextureCache();
  14012. texture.isReady = true;
  14013. };
  14014. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14015. if (compression === void 0) { compression = null; }
  14016. var gl = this._gl;
  14017. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14018. texture.isCube = true;
  14019. texture.generateMipMaps = generateMipMaps;
  14020. texture.format = format;
  14021. texture.type = type;
  14022. if (!this._doNotHandleContextLost) {
  14023. texture._bufferViewArray = data;
  14024. }
  14025. var textureType = this._getWebGLTextureType(type);
  14026. var internalFormat = this._getInternalFormat(format);
  14027. if (internalFormat === gl.RGB) {
  14028. internalFormat = gl.RGBA;
  14029. }
  14030. var width = size;
  14031. var height = width;
  14032. texture.width = width;
  14033. texture.height = height;
  14034. // Double check on POT to generate Mips.
  14035. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14036. if (!isPot) {
  14037. generateMipMaps = false;
  14038. }
  14039. // Upload data if needed. The texture won't be ready until then.
  14040. if (data) {
  14041. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14042. }
  14043. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14044. // Filters
  14045. if (data && generateMipMaps) {
  14046. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14047. }
  14048. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14051. }
  14052. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14055. }
  14056. else {
  14057. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14060. }
  14061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14063. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14064. return texture;
  14065. };
  14066. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14067. var _this = this;
  14068. if (onLoad === void 0) { onLoad = null; }
  14069. if (onError === void 0) { onError = null; }
  14070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14071. if (invertY === void 0) { invertY = false; }
  14072. var gl = this._gl;
  14073. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14074. scene._addPendingData(texture);
  14075. texture.url = url;
  14076. this._internalTexturesCache.push(texture);
  14077. var onerror = function (request, exception) {
  14078. scene._removePendingData(texture);
  14079. if (onError && request) {
  14080. onError(request.status + " " + request.statusText, exception);
  14081. }
  14082. };
  14083. var internalCallback = function (data) {
  14084. var width = texture.width;
  14085. var faceDataArrays = callback(data);
  14086. if (!faceDataArrays) {
  14087. return;
  14088. }
  14089. if (mipmmapGenerator) {
  14090. var textureType = _this._getWebGLTextureType(type);
  14091. var internalFormat = _this._getInternalFormat(format);
  14092. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14093. var needConversion = false;
  14094. if (internalFormat === gl.RGB) {
  14095. internalFormat = gl.RGBA;
  14096. needConversion = true;
  14097. }
  14098. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14099. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14100. var mipData = mipmmapGenerator(faceDataArrays);
  14101. for (var level = 0; level < mipData.length; level++) {
  14102. var mipSize = width >> level;
  14103. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14104. var mipFaceData = mipData[level][faceIndex];
  14105. if (needConversion) {
  14106. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14107. }
  14108. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14109. }
  14110. }
  14111. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14112. }
  14113. else {
  14114. texture.generateMipMaps = !noMipmap;
  14115. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14116. }
  14117. texture.isReady = true;
  14118. // this.resetTextureCache();
  14119. scene._removePendingData(texture);
  14120. if (onLoad) {
  14121. onLoad();
  14122. }
  14123. };
  14124. this._loadFile(url, function (data) {
  14125. internalCallback(data);
  14126. }, undefined, scene.database, true, onerror);
  14127. return texture;
  14128. };
  14129. ;
  14130. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14131. if (compression === void 0) { compression = null; }
  14132. var internalFormat = this._getInternalFormat(format);
  14133. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14134. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14135. if (!this._doNotHandleContextLost) {
  14136. texture._bufferView = data;
  14137. texture.format = format;
  14138. texture.invertY = invertY;
  14139. texture._compression = compression;
  14140. }
  14141. if (texture.width % 4 !== 0) {
  14142. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14143. }
  14144. if (compression && data) {
  14145. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14146. }
  14147. else {
  14148. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14149. }
  14150. if (texture.generateMipMaps) {
  14151. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14152. }
  14153. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14154. // this.resetTextureCache();
  14155. texture.isReady = true;
  14156. };
  14157. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14158. if (compression === void 0) { compression = null; }
  14159. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14160. texture.baseWidth = width;
  14161. texture.baseHeight = height;
  14162. texture.baseDepth = depth;
  14163. texture.width = width;
  14164. texture.height = height;
  14165. texture.depth = depth;
  14166. texture.format = format;
  14167. texture.generateMipMaps = generateMipMaps;
  14168. texture.samplingMode = samplingMode;
  14169. texture.is3D = true;
  14170. if (!this._doNotHandleContextLost) {
  14171. texture._bufferView = data;
  14172. }
  14173. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14174. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14175. // Filters
  14176. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14177. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14179. if (generateMipMaps) {
  14180. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14181. }
  14182. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14183. this._internalTexturesCache.push(texture);
  14184. return texture;
  14185. };
  14186. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14187. var gl = this._gl;
  14188. if (!gl) {
  14189. return;
  14190. }
  14191. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14194. if (!noMipmap && !isCompressed) {
  14195. gl.generateMipmap(gl.TEXTURE_2D);
  14196. }
  14197. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14198. // this.resetTextureCache();
  14199. if (scene) {
  14200. scene._removePendingData(texture);
  14201. }
  14202. texture.onLoadedObservable.notifyObservers(texture);
  14203. texture.onLoadedObservable.clear();
  14204. };
  14205. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14206. var _this = this;
  14207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14208. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14209. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14210. var gl = this._gl;
  14211. if (!gl) {
  14212. return;
  14213. }
  14214. if (!texture._webGLTexture) {
  14215. // this.resetTextureCache();
  14216. if (scene) {
  14217. scene._removePendingData(texture);
  14218. }
  14219. return;
  14220. }
  14221. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14222. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14223. texture.baseWidth = width;
  14224. texture.baseHeight = height;
  14225. texture.width = potWidth;
  14226. texture.height = potHeight;
  14227. texture.isReady = true;
  14228. if (processFunction(potWidth, potHeight, function () {
  14229. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14230. })) {
  14231. // Returning as texture needs extra async steps
  14232. return;
  14233. }
  14234. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14235. };
  14236. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14237. // Create new RGBA data container.
  14238. var rgbaData;
  14239. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14240. rgbaData = new Float32Array(width * height * 4);
  14241. }
  14242. else {
  14243. rgbaData = new Uint32Array(width * height * 4);
  14244. }
  14245. // Convert each pixel.
  14246. for (var x = 0; x < width; x++) {
  14247. for (var y = 0; y < height; y++) {
  14248. var index = (y * width + x) * 3;
  14249. var newIndex = (y * width + x) * 4;
  14250. // Map Old Value to new value.
  14251. rgbaData[newIndex + 0] = rgbData[index + 0];
  14252. rgbaData[newIndex + 1] = rgbData[index + 1];
  14253. rgbaData[newIndex + 2] = rgbData[index + 2];
  14254. // Add fully opaque alpha channel.
  14255. rgbaData[newIndex + 3] = 1;
  14256. }
  14257. }
  14258. return rgbaData;
  14259. };
  14260. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14261. var gl = this._gl;
  14262. if (texture._framebuffer) {
  14263. gl.deleteFramebuffer(texture._framebuffer);
  14264. texture._framebuffer = null;
  14265. }
  14266. if (texture._depthStencilBuffer) {
  14267. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14268. texture._depthStencilBuffer = null;
  14269. }
  14270. if (texture._MSAAFramebuffer) {
  14271. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14272. texture._MSAAFramebuffer = null;
  14273. }
  14274. if (texture._MSAARenderBuffer) {
  14275. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14276. texture._MSAARenderBuffer = null;
  14277. }
  14278. };
  14279. Engine.prototype._releaseTexture = function (texture) {
  14280. var gl = this._gl;
  14281. this._releaseFramebufferObjects(texture);
  14282. gl.deleteTexture(texture._webGLTexture);
  14283. // Unbind channels
  14284. this.unbindAllTextures();
  14285. var index = this._internalTexturesCache.indexOf(texture);
  14286. if (index !== -1) {
  14287. this._internalTexturesCache.splice(index, 1);
  14288. }
  14289. // Integrated fixed lod samplers.
  14290. if (texture._lodTextureHigh) {
  14291. texture._lodTextureHigh.dispose();
  14292. }
  14293. if (texture._lodTextureMid) {
  14294. texture._lodTextureMid.dispose();
  14295. }
  14296. if (texture._lodTextureLow) {
  14297. texture._lodTextureLow.dispose();
  14298. }
  14299. };
  14300. Engine.prototype.setProgram = function (program) {
  14301. if (this._currentProgram !== program) {
  14302. this._gl.useProgram(program);
  14303. this._currentProgram = program;
  14304. }
  14305. };
  14306. Engine.prototype.bindSamplers = function (effect) {
  14307. this.setProgram(effect.getProgram());
  14308. var samplers = effect.getSamplers();
  14309. for (var index = 0; index < samplers.length; index++) {
  14310. var uniform = effect.getUniform(samplers[index]);
  14311. if (uniform) {
  14312. this._boundUniforms[index] = uniform;
  14313. }
  14314. }
  14315. this._currentEffect = null;
  14316. };
  14317. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14318. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14319. return;
  14320. }
  14321. // Remove
  14322. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14323. // Bind last to it
  14324. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14325. // Bind to dummy
  14326. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14327. };
  14328. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14329. if (!internalTexture) {
  14330. return -1;
  14331. }
  14332. internalTexture._initialSlot = channel;
  14333. if (this.disableTextureBindingOptimization) {
  14334. if (channel !== internalTexture._designatedSlot) {
  14335. this._textureCollisions.addCount(1, false);
  14336. }
  14337. }
  14338. else {
  14339. if (channel !== internalTexture._designatedSlot) {
  14340. if (internalTexture._designatedSlot > -1) {
  14341. return internalTexture._designatedSlot;
  14342. }
  14343. else {
  14344. // No slot for this texture, let's pick a new one (if we find a free slot)
  14345. if (this._nextFreeTextureSlots.length) {
  14346. return this._nextFreeTextureSlots[0];
  14347. }
  14348. // We need to recycle the oldest bound texture, sorry.
  14349. this._textureCollisions.addCount(1, false);
  14350. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14351. }
  14352. }
  14353. }
  14354. return channel;
  14355. };
  14356. Engine.prototype._linkTrackers = function (previous, next) {
  14357. previous.next = next;
  14358. next.previous = previous;
  14359. };
  14360. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14361. var currentSlot = internalTexture._designatedSlot;
  14362. if (currentSlot === -1) {
  14363. return -1;
  14364. }
  14365. internalTexture._designatedSlot = -1;
  14366. if (this.disableTextureBindingOptimization) {
  14367. return -1;
  14368. }
  14369. // Remove from bound list
  14370. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14371. // Free the slot
  14372. this._boundTexturesCache[currentSlot] = null;
  14373. this._nextFreeTextureSlots.push(currentSlot);
  14374. return currentSlot;
  14375. };
  14376. Engine.prototype._activateCurrentTexture = function () {
  14377. if (this._currentTextureChannel !== this._activeChannel) {
  14378. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14379. this._currentTextureChannel = this._activeChannel;
  14380. }
  14381. };
  14382. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14383. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14384. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14385. this._activeChannel = texture._designatedSlot;
  14386. }
  14387. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14388. var isTextureForRendering = texture && texture._initialSlot > -1;
  14389. if (currentTextureBound !== texture) {
  14390. if (currentTextureBound) {
  14391. this._removeDesignatedSlot(currentTextureBound);
  14392. }
  14393. this._activateCurrentTexture();
  14394. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14395. this._boundTexturesCache[this._activeChannel] = texture;
  14396. if (texture) {
  14397. if (!this.disableTextureBindingOptimization) {
  14398. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14399. if (slotIndex > -1) {
  14400. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14401. }
  14402. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14403. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14404. }
  14405. texture._designatedSlot = this._activeChannel;
  14406. }
  14407. }
  14408. else if (forTextureDataUpdate) {
  14409. this._activateCurrentTexture();
  14410. }
  14411. if (isTextureForRendering && !forTextureDataUpdate) {
  14412. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14413. }
  14414. };
  14415. Engine.prototype._bindTexture = function (channel, texture) {
  14416. if (channel < 0) {
  14417. return;
  14418. }
  14419. if (texture) {
  14420. channel = this._getCorrectTextureChannel(channel, texture);
  14421. }
  14422. this._activeChannel = channel;
  14423. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14424. };
  14425. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14426. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14427. };
  14428. Engine.prototype.unbindAllTextures = function () {
  14429. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14430. this._activeChannel = channel;
  14431. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14433. if (this.webGLVersion > 1) {
  14434. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14435. }
  14436. }
  14437. };
  14438. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14439. if (channel < 0) {
  14440. return;
  14441. }
  14442. if (uniform) {
  14443. this._boundUniforms[channel] = uniform;
  14444. }
  14445. this._setTexture(channel, texture);
  14446. };
  14447. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14448. var uniform = this._boundUniforms[sourceSlot];
  14449. if (uniform._currentState === destination) {
  14450. return;
  14451. }
  14452. this._gl.uniform1i(uniform, destination);
  14453. uniform._currentState = destination;
  14454. };
  14455. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14456. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14457. // Not ready?
  14458. if (!texture) {
  14459. if (this._boundTexturesCache[channel] != null) {
  14460. this._activeChannel = channel;
  14461. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14463. if (this.webGLVersion > 1) {
  14464. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14465. }
  14466. }
  14467. return false;
  14468. }
  14469. // Video
  14470. if (texture.video) {
  14471. this._activeChannel = channel;
  14472. texture.update();
  14473. }
  14474. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14475. texture.delayLoad();
  14476. return false;
  14477. }
  14478. var internalTexture;
  14479. if (texture.isReady()) {
  14480. internalTexture = texture.getInternalTexture();
  14481. }
  14482. else if (texture.isCube) {
  14483. internalTexture = this.emptyCubeTexture;
  14484. }
  14485. else if (texture.is3D) {
  14486. internalTexture = this.emptyTexture3D;
  14487. }
  14488. else {
  14489. internalTexture = this.emptyTexture;
  14490. }
  14491. if (!isPartOfTextureArray) {
  14492. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14493. }
  14494. if (this._boundTexturesCache[channel] === internalTexture) {
  14495. this._moveBoundTextureOnTop(internalTexture);
  14496. if (!isPartOfTextureArray) {
  14497. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14498. }
  14499. return false;
  14500. }
  14501. this._activeChannel = channel;
  14502. if (internalTexture && internalTexture.is3D) {
  14503. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14504. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14505. internalTexture._cachedWrapU = texture.wrapU;
  14506. switch (texture.wrapU) {
  14507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14508. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14509. break;
  14510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14511. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14512. break;
  14513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14514. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14515. break;
  14516. }
  14517. }
  14518. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14519. internalTexture._cachedWrapV = texture.wrapV;
  14520. switch (texture.wrapV) {
  14521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14522. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14523. break;
  14524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14525. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14526. break;
  14527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14528. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14529. break;
  14530. }
  14531. }
  14532. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14533. internalTexture._cachedWrapR = texture.wrapR;
  14534. switch (texture.wrapR) {
  14535. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14537. break;
  14538. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14540. break;
  14541. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14542. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14543. break;
  14544. }
  14545. }
  14546. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14547. }
  14548. else if (internalTexture && internalTexture.isCube) {
  14549. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14550. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14551. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14552. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14553. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14554. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14555. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14556. }
  14557. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14558. }
  14559. else {
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14561. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14562. internalTexture._cachedWrapU = texture.wrapU;
  14563. switch (texture.wrapU) {
  14564. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14566. break;
  14567. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14569. break;
  14570. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14571. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14572. break;
  14573. }
  14574. }
  14575. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14576. internalTexture._cachedWrapV = texture.wrapV;
  14577. switch (texture.wrapV) {
  14578. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14580. break;
  14581. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14583. break;
  14584. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14585. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14586. break;
  14587. }
  14588. }
  14589. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14590. }
  14591. return true;
  14592. };
  14593. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14594. if (channel < 0 || !uniform) {
  14595. return;
  14596. }
  14597. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14598. this._textureUnits = new Int32Array(textures.length);
  14599. }
  14600. for (var i = 0; i < textures.length; i++) {
  14601. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14602. }
  14603. this._gl.uniform1iv(uniform, this._textureUnits);
  14604. for (var index = 0; index < textures.length; index++) {
  14605. this._setTexture(this._textureUnits[index], textures[index], true);
  14606. }
  14607. };
  14608. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14609. var internalTexture = texture.getInternalTexture();
  14610. if (!internalTexture) {
  14611. return;
  14612. }
  14613. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14614. var value = texture.anisotropicFilteringLevel;
  14615. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14616. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14617. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14618. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14619. }
  14620. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14621. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14622. internalTexture._cachedAnisotropicFilteringLevel = value;
  14623. }
  14624. };
  14625. Engine.prototype.readPixels = function (x, y, width, height) {
  14626. var data = new Uint8Array(height * width * 4);
  14627. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14628. return data;
  14629. };
  14630. /**
  14631. * Add an externaly attached data from its key.
  14632. * This method call will fail and return false, if such key already exists.
  14633. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14634. * @param key the unique key that identifies the data
  14635. * @param data the data object to associate to the key for this Engine instance
  14636. * @return true if no such key were already present and the data was added successfully, false otherwise
  14637. */
  14638. Engine.prototype.addExternalData = function (key, data) {
  14639. if (!this._externalData) {
  14640. this._externalData = new BABYLON.StringDictionary();
  14641. }
  14642. return this._externalData.add(key, data);
  14643. };
  14644. /**
  14645. * Get an externaly attached data from its key
  14646. * @param key the unique key that identifies the data
  14647. * @return the associated data, if present (can be null), or undefined if not present
  14648. */
  14649. Engine.prototype.getExternalData = function (key) {
  14650. if (!this._externalData) {
  14651. this._externalData = new BABYLON.StringDictionary();
  14652. }
  14653. return this._externalData.get(key);
  14654. };
  14655. /**
  14656. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14657. * @param key the unique key that identifies the data
  14658. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14659. * @return the associated data, can be null if the factory returned null.
  14660. */
  14661. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14662. if (!this._externalData) {
  14663. this._externalData = new BABYLON.StringDictionary();
  14664. }
  14665. return this._externalData.getOrAddWithFactory(key, factory);
  14666. };
  14667. /**
  14668. * Remove an externaly attached data from the Engine instance
  14669. * @param key the unique key that identifies the data
  14670. * @return true if the data was successfully removed, false if it doesn't exist
  14671. */
  14672. Engine.prototype.removeExternalData = function (key) {
  14673. if (!this._externalData) {
  14674. this._externalData = new BABYLON.StringDictionary();
  14675. }
  14676. return this._externalData.remove(key);
  14677. };
  14678. Engine.prototype.unbindAllAttributes = function () {
  14679. if (this._mustWipeVertexAttributes) {
  14680. this._mustWipeVertexAttributes = false;
  14681. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14682. this._gl.disableVertexAttribArray(i);
  14683. this._vertexAttribArraysEnabled[i] = false;
  14684. this._currentBufferPointers[i].active = false;
  14685. }
  14686. return;
  14687. }
  14688. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14689. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14690. continue;
  14691. }
  14692. this._gl.disableVertexAttribArray(i);
  14693. this._vertexAttribArraysEnabled[i] = false;
  14694. this._currentBufferPointers[i].active = false;
  14695. }
  14696. };
  14697. Engine.prototype.releaseEffects = function () {
  14698. for (var name in this._compiledEffects) {
  14699. this._deleteProgram(this._compiledEffects[name]._program);
  14700. }
  14701. this._compiledEffects = {};
  14702. };
  14703. // Dispose
  14704. Engine.prototype.dispose = function () {
  14705. this.hideLoadingUI();
  14706. this.stopRenderLoop();
  14707. // Release postProcesses
  14708. while (this.postProcesses.length) {
  14709. this.postProcesses[0].dispose();
  14710. }
  14711. // Empty texture
  14712. if (this._emptyTexture) {
  14713. this._releaseTexture(this._emptyTexture);
  14714. this._emptyTexture = null;
  14715. }
  14716. if (this._emptyCubeTexture) {
  14717. this._releaseTexture(this._emptyCubeTexture);
  14718. this._emptyCubeTexture = null;
  14719. }
  14720. // Rescale PP
  14721. if (this._rescalePostProcess) {
  14722. this._rescalePostProcess.dispose();
  14723. }
  14724. // Release scenes
  14725. while (this.scenes.length) {
  14726. this.scenes[0].dispose();
  14727. }
  14728. // Release audio engine
  14729. if (Engine.audioEngine) {
  14730. Engine.audioEngine.dispose();
  14731. }
  14732. // Release effects
  14733. this.releaseEffects();
  14734. // Unbind
  14735. this.unbindAllAttributes();
  14736. if (this._dummyFramebuffer) {
  14737. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14738. }
  14739. //WebVR
  14740. this.disableVR();
  14741. // Events
  14742. if (BABYLON.Tools.IsWindowObjectExist()) {
  14743. window.removeEventListener("blur", this._onBlur);
  14744. window.removeEventListener("focus", this._onFocus);
  14745. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14746. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14747. if (this._renderingCanvas) {
  14748. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14749. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14750. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14751. if (!this._doNotHandleContextLost) {
  14752. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14753. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14754. }
  14755. }
  14756. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14757. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14758. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14759. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14760. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14761. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14762. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14763. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14764. if (this._onVrDisplayConnect) {
  14765. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14766. if (this._onVrDisplayDisconnect) {
  14767. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14768. }
  14769. if (this._onVrDisplayPresentChange) {
  14770. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14771. }
  14772. this._onVrDisplayConnect = null;
  14773. this._onVrDisplayDisconnect = null;
  14774. }
  14775. }
  14776. // Remove from Instances
  14777. var index = Engine.Instances.indexOf(this);
  14778. if (index >= 0) {
  14779. Engine.Instances.splice(index, 1);
  14780. }
  14781. this._workingCanvas = null;
  14782. this._workingContext = null;
  14783. this._currentBufferPointers = [];
  14784. this._renderingCanvas = null;
  14785. this._currentProgram = null;
  14786. this.onResizeObservable.clear();
  14787. this.onCanvasBlurObservable.clear();
  14788. this.onCanvasFocusObservable.clear();
  14789. this.onCanvasPointerOutObservable.clear();
  14790. this.onBeginFrameObservable.clear();
  14791. this.onEndFrameObservable.clear();
  14792. BABYLON.Effect.ResetCache();
  14793. // Abort active requests
  14794. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14795. var request = _a[_i];
  14796. request.abort();
  14797. }
  14798. };
  14799. // Loading screen
  14800. Engine.prototype.displayLoadingUI = function () {
  14801. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14802. return;
  14803. }
  14804. var loadingScreen = this.loadingScreen;
  14805. if (loadingScreen) {
  14806. loadingScreen.displayLoadingUI();
  14807. }
  14808. };
  14809. Engine.prototype.hideLoadingUI = function () {
  14810. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14811. return;
  14812. }
  14813. var loadingScreen = this.loadingScreen;
  14814. if (loadingScreen) {
  14815. loadingScreen.hideLoadingUI();
  14816. }
  14817. };
  14818. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14819. get: function () {
  14820. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14821. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14822. return this._loadingScreen;
  14823. },
  14824. set: function (loadingScreen) {
  14825. this._loadingScreen = loadingScreen;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14831. set: function (text) {
  14832. this.loadingScreen.loadingUIText = text;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14838. set: function (color) {
  14839. this.loadingScreen.loadingUIBackgroundColor = color;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Engine.prototype.attachContextLostEvent = function (callback) {
  14845. if (this._renderingCanvas) {
  14846. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14847. }
  14848. };
  14849. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14850. if (this._renderingCanvas) {
  14851. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14852. }
  14853. };
  14854. Engine.prototype.getVertexShaderSource = function (program) {
  14855. var shaders = this._gl.getAttachedShaders(program);
  14856. if (!shaders) {
  14857. return null;
  14858. }
  14859. return this._gl.getShaderSource(shaders[0]);
  14860. };
  14861. Engine.prototype.getFragmentShaderSource = function (program) {
  14862. var shaders = this._gl.getAttachedShaders(program);
  14863. if (!shaders) {
  14864. return null;
  14865. }
  14866. return this._gl.getShaderSource(shaders[1]);
  14867. };
  14868. Engine.prototype.getError = function () {
  14869. return this._gl.getError();
  14870. };
  14871. // FPS
  14872. Engine.prototype.getFps = function () {
  14873. return this._fps;
  14874. };
  14875. Engine.prototype.getDeltaTime = function () {
  14876. return this._deltaTime;
  14877. };
  14878. Engine.prototype._measureFps = function () {
  14879. this._performanceMonitor.sampleFrame();
  14880. this._fps = this._performanceMonitor.averageFPS;
  14881. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14882. };
  14883. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14884. if (faceIndex === void 0) { faceIndex = -1; }
  14885. var gl = this._gl;
  14886. if (!this._dummyFramebuffer) {
  14887. var dummy = gl.createFramebuffer();
  14888. if (!dummy) {
  14889. throw new Error("Unable to create dummy framebuffer");
  14890. }
  14891. this._dummyFramebuffer = dummy;
  14892. }
  14893. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14894. if (faceIndex > -1) {
  14895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14896. }
  14897. else {
  14898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14899. }
  14900. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14901. var buffer;
  14902. switch (readType) {
  14903. case gl.UNSIGNED_BYTE:
  14904. buffer = new Uint8Array(4 * width * height);
  14905. readType = gl.UNSIGNED_BYTE;
  14906. break;
  14907. default:
  14908. buffer = new Float32Array(4 * width * height);
  14909. readType = gl.FLOAT;
  14910. break;
  14911. }
  14912. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14913. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14914. return buffer;
  14915. };
  14916. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14917. if (this._webGLVersion > 1) {
  14918. return this._caps.colorBufferFloat;
  14919. }
  14920. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14921. };
  14922. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14923. if (this._webGLVersion > 1) {
  14924. return this._caps.colorBufferFloat;
  14925. }
  14926. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14927. };
  14928. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14929. Engine.prototype._canRenderToFramebuffer = function (type) {
  14930. var gl = this._gl;
  14931. //clear existing errors
  14932. while (gl.getError() !== gl.NO_ERROR) { }
  14933. var successful = true;
  14934. var texture = gl.createTexture();
  14935. gl.bindTexture(gl.TEXTURE_2D, texture);
  14936. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14939. var fb = gl.createFramebuffer();
  14940. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14941. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14942. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14943. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14944. successful = successful && (gl.getError() === gl.NO_ERROR);
  14945. //try render by clearing frame buffer's color buffer
  14946. if (successful) {
  14947. gl.clear(gl.COLOR_BUFFER_BIT);
  14948. successful = successful && (gl.getError() === gl.NO_ERROR);
  14949. }
  14950. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14951. if (successful) {
  14952. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14953. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14954. var readFormat = gl.RGBA;
  14955. var readType = gl.UNSIGNED_BYTE;
  14956. var buffer = new Uint8Array(4);
  14957. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14958. successful = successful && (gl.getError() === gl.NO_ERROR);
  14959. }
  14960. //clean up
  14961. gl.deleteTexture(texture);
  14962. gl.deleteFramebuffer(fb);
  14963. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14964. //clear accumulated errors
  14965. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14966. return successful;
  14967. };
  14968. Engine.prototype._getWebGLTextureType = function (type) {
  14969. if (type === Engine.TEXTURETYPE_FLOAT) {
  14970. return this._gl.FLOAT;
  14971. }
  14972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14973. // Add Half Float Constant.
  14974. return this._gl.HALF_FLOAT_OES;
  14975. }
  14976. return this._gl.UNSIGNED_BYTE;
  14977. };
  14978. ;
  14979. /** @ignore */
  14980. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14981. if (this._webGLVersion === 1) {
  14982. return this._gl.RGBA;
  14983. }
  14984. if (type === Engine.TEXTURETYPE_FLOAT) {
  14985. if (format) {
  14986. switch (format) {
  14987. case Engine.TEXTUREFORMAT_R32F:
  14988. return this._gl.R32F;
  14989. case Engine.TEXTUREFORMAT_RG32F:
  14990. return this._gl.RG32F;
  14991. case Engine.TEXTUREFORMAT_RGB32F:
  14992. return this._gl.RGB32F;
  14993. }
  14994. }
  14995. return this._gl.RGBA32F;
  14996. }
  14997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14998. return this._gl.RGBA16F;
  14999. }
  15000. return this._gl.RGBA;
  15001. };
  15002. ;
  15003. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15004. if (type === Engine.TEXTURETYPE_FLOAT) {
  15005. return this._gl.RGBA32F;
  15006. }
  15007. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15008. return this._gl.RGBA16F;
  15009. }
  15010. return this._gl.RGBA8;
  15011. };
  15012. ;
  15013. Engine.prototype.createQuery = function () {
  15014. return this._gl.createQuery();
  15015. };
  15016. Engine.prototype.deleteQuery = function (query) {
  15017. this._gl.deleteQuery(query);
  15018. return this;
  15019. };
  15020. Engine.prototype.isQueryResultAvailable = function (query) {
  15021. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15022. };
  15023. Engine.prototype.getQueryResult = function (query) {
  15024. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15025. };
  15026. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15027. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15028. this._gl.beginQuery(glAlgorithm, query);
  15029. return this;
  15030. };
  15031. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15032. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15033. this._gl.endQuery(glAlgorithm);
  15034. return this;
  15035. };
  15036. /* Time queries */
  15037. Engine.prototype._createTimeQuery = function () {
  15038. var timerQuery = this._caps.timerQuery;
  15039. if (timerQuery.createQueryEXT) {
  15040. return timerQuery.createQueryEXT();
  15041. }
  15042. return this.createQuery();
  15043. };
  15044. Engine.prototype._deleteTimeQuery = function (query) {
  15045. var timerQuery = this._caps.timerQuery;
  15046. if (timerQuery.deleteQueryEXT) {
  15047. timerQuery.deleteQueryEXT(query);
  15048. return;
  15049. }
  15050. this.deleteQuery(query);
  15051. };
  15052. Engine.prototype._getTimeQueryResult = function (query) {
  15053. var timerQuery = this._caps.timerQuery;
  15054. if (timerQuery.getQueryObjectEXT) {
  15055. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15056. }
  15057. return this.getQueryResult(query);
  15058. };
  15059. Engine.prototype._getTimeQueryAvailability = function (query) {
  15060. var timerQuery = this._caps.timerQuery;
  15061. if (timerQuery.getQueryObjectEXT) {
  15062. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15063. }
  15064. return this.isQueryResultAvailable(query);
  15065. };
  15066. Engine.prototype.startTimeQuery = function () {
  15067. var timerQuery = this._caps.timerQuery;
  15068. if (!timerQuery) {
  15069. return null;
  15070. }
  15071. var token = new BABYLON._TimeToken();
  15072. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15073. if (this._caps.canUseTimestampForTimerQuery) {
  15074. token._startTimeQuery = this._createTimeQuery();
  15075. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15076. }
  15077. else {
  15078. if (this._currentNonTimestampToken) {
  15079. return this._currentNonTimestampToken;
  15080. }
  15081. token._timeElapsedQuery = this._createTimeQuery();
  15082. if (timerQuery.beginQueryEXT) {
  15083. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15084. }
  15085. else {
  15086. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15087. }
  15088. this._currentNonTimestampToken = token;
  15089. }
  15090. return token;
  15091. };
  15092. Engine.prototype.endTimeQuery = function (token) {
  15093. var timerQuery = this._caps.timerQuery;
  15094. if (!timerQuery || !token) {
  15095. return -1;
  15096. }
  15097. if (this._caps.canUseTimestampForTimerQuery) {
  15098. if (!token._startTimeQuery) {
  15099. return -1;
  15100. }
  15101. if (!token._endTimeQuery) {
  15102. token._endTimeQuery = this._createTimeQuery();
  15103. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15104. }
  15105. }
  15106. else if (!token._timeElapsedQueryEnded) {
  15107. if (!token._timeElapsedQuery) {
  15108. return -1;
  15109. }
  15110. if (timerQuery.endQueryEXT) {
  15111. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15112. }
  15113. else {
  15114. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15115. }
  15116. token._timeElapsedQueryEnded = true;
  15117. }
  15118. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15119. var available = false;
  15120. if (token._endTimeQuery) {
  15121. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15122. }
  15123. else if (token._timeElapsedQuery) {
  15124. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15125. }
  15126. if (available && !disjoint) {
  15127. var result = 0;
  15128. if (this._caps.canUseTimestampForTimerQuery) {
  15129. if (!token._startTimeQuery || !token._endTimeQuery) {
  15130. return -1;
  15131. }
  15132. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15133. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15134. result = timeEnd - timeStart;
  15135. this._deleteTimeQuery(token._startTimeQuery);
  15136. this._deleteTimeQuery(token._endTimeQuery);
  15137. token._startTimeQuery = null;
  15138. token._endTimeQuery = null;
  15139. }
  15140. else {
  15141. if (!token._timeElapsedQuery) {
  15142. return -1;
  15143. }
  15144. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15145. this._deleteTimeQuery(token._timeElapsedQuery);
  15146. token._timeElapsedQuery = null;
  15147. token._timeElapsedQueryEnded = false;
  15148. this._currentNonTimestampToken = null;
  15149. }
  15150. return result;
  15151. }
  15152. return -1;
  15153. };
  15154. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15155. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15156. };
  15157. // Transform feedback
  15158. Engine.prototype.createTransformFeedback = function () {
  15159. return this._gl.createTransformFeedback();
  15160. };
  15161. Engine.prototype.deleteTransformFeedback = function (value) {
  15162. this._gl.deleteTransformFeedback(value);
  15163. };
  15164. Engine.prototype.bindTransformFeedback = function (value) {
  15165. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15166. };
  15167. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15168. if (usePoints === void 0) { usePoints = true; }
  15169. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15170. };
  15171. Engine.prototype.endTransformFeedback = function () {
  15172. this._gl.endTransformFeedback();
  15173. };
  15174. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15175. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15176. };
  15177. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15178. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15179. };
  15180. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15181. var _this = this;
  15182. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15183. this._activeRequests.push(request);
  15184. request.onCompleteObservable.add(function (request) {
  15185. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15186. });
  15187. return request;
  15188. };
  15189. /** @ignore */
  15190. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15191. var _this = this;
  15192. return new Promise(function (resolve, reject) {
  15193. _this._loadFile(url, function (data) {
  15194. resolve(data);
  15195. }, undefined, database, useArrayBuffer, function (request, exception) {
  15196. reject(exception);
  15197. });
  15198. });
  15199. };
  15200. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15201. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15202. var onload = function (data) {
  15203. loadedFiles[index] = data;
  15204. loadedFiles._internalCount++;
  15205. if (loadedFiles._internalCount === 6) {
  15206. onfinish(loadedFiles);
  15207. }
  15208. };
  15209. var onerror = function (request, exception) {
  15210. if (onErrorCallBack && request) {
  15211. onErrorCallBack(request.status + " " + request.statusText, exception);
  15212. }
  15213. };
  15214. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15215. };
  15216. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15217. if (onError === void 0) { onError = null; }
  15218. var loadedFiles = [];
  15219. loadedFiles._internalCount = 0;
  15220. for (var index = 0; index < 6; index++) {
  15221. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15222. }
  15223. };
  15224. // Statics
  15225. Engine.isSupported = function () {
  15226. try {
  15227. var tempcanvas = document.createElement("canvas");
  15228. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15229. return gl != null && !!window.WebGLRenderingContext;
  15230. }
  15231. catch (e) {
  15232. return false;
  15233. }
  15234. };
  15235. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15236. Engine.ExceptionList = [
  15237. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15238. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15239. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15240. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15241. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15242. ];
  15243. Engine.Instances = new Array();
  15244. // Const statics
  15245. Engine._ALPHA_DISABLE = 0;
  15246. Engine._ALPHA_ADD = 1;
  15247. Engine._ALPHA_COMBINE = 2;
  15248. Engine._ALPHA_SUBTRACT = 3;
  15249. Engine._ALPHA_MULTIPLY = 4;
  15250. Engine._ALPHA_MAXIMIZED = 5;
  15251. Engine._ALPHA_ONEONE = 6;
  15252. Engine._ALPHA_PREMULTIPLIED = 7;
  15253. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15254. Engine._ALPHA_INTERPOLATE = 9;
  15255. Engine._ALPHA_SCREENMODE = 10;
  15256. Engine._DELAYLOADSTATE_NONE = 0;
  15257. Engine._DELAYLOADSTATE_LOADED = 1;
  15258. Engine._DELAYLOADSTATE_LOADING = 2;
  15259. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15260. Engine._TEXTUREFORMAT_ALPHA = 0;
  15261. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15262. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15263. Engine._TEXTUREFORMAT_RGB = 4;
  15264. Engine._TEXTUREFORMAT_RGBA = 5;
  15265. Engine._TEXTUREFORMAT_R32F = 6;
  15266. Engine._TEXTUREFORMAT_RG32F = 7;
  15267. Engine._TEXTUREFORMAT_RGB32F = 8;
  15268. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15269. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15270. Engine._TEXTURETYPE_FLOAT = 1;
  15271. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15272. // Depht or Stencil test Constants.
  15273. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15274. 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.
  15275. 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.
  15276. 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.
  15277. 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.
  15278. 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.
  15279. 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.
  15280. 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.
  15281. // Stencil Actions Constants.
  15282. Engine._KEEP = 0x1E00;
  15283. Engine._REPLACE = 0x1E01;
  15284. Engine._INCR = 0x1E02;
  15285. Engine._DECR = 0x1E03;
  15286. Engine._INVERT = 0x150A;
  15287. Engine._INCR_WRAP = 0x8507;
  15288. Engine._DECR_WRAP = 0x8508;
  15289. // Texture rescaling mode
  15290. Engine._SCALEMODE_FLOOR = 1;
  15291. Engine._SCALEMODE_NEAREST = 2;
  15292. Engine._SCALEMODE_CEILING = 3;
  15293. // Updatable statics so stick with vars here
  15294. Engine.CollisionsEpsilon = 0.001;
  15295. Engine.CodeRepository = "src/";
  15296. Engine.ShadersRepository = "src/Shaders/";
  15297. return Engine;
  15298. }());
  15299. BABYLON.Engine = Engine;
  15300. })(BABYLON || (BABYLON = {}));
  15301. //# sourceMappingURL=babylon.engine.js.map
  15302. var BABYLON;
  15303. (function (BABYLON) {
  15304. /**
  15305. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15306. */
  15307. var Node = /** @class */ (function () {
  15308. /**
  15309. * Creates a new Node
  15310. * @param {string} name - the name and id to be given to this node
  15311. * @param {BABYLON.Scene} the scene this node will be added to
  15312. */
  15313. function Node(name, scene) {
  15314. if (scene === void 0) { scene = null; }
  15315. /**
  15316. * Gets or sets a string used to store user defined state for the node
  15317. */
  15318. this.state = "";
  15319. /**
  15320. * Gets or sets an object used to store user defined information for the node
  15321. */
  15322. this.metadata = null;
  15323. /**
  15324. * Gets or sets a boolean used to define if the node must be serialized
  15325. */
  15326. this.doNotSerialize = false;
  15327. /** @ignore */
  15328. this._isDisposed = false;
  15329. /**
  15330. * Gets a list of {BABYLON.Animation} associated with the node
  15331. */
  15332. this.animations = new Array();
  15333. this._ranges = {};
  15334. this._isEnabled = true;
  15335. this._isReady = true;
  15336. /** @ignore */
  15337. this._currentRenderId = -1;
  15338. this._parentRenderId = -1;
  15339. /**
  15340. * An event triggered when the mesh is disposed
  15341. * @type {BABYLON.Observable}
  15342. */
  15343. this.onDisposeObservable = new BABYLON.Observable();
  15344. // Behaviors
  15345. this._behaviors = new Array();
  15346. this.name = name;
  15347. this.id = name;
  15348. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15349. this.uniqueId = this._scene.getUniqueId();
  15350. this._initCache();
  15351. }
  15352. /**
  15353. * Gets a boolean indicating if the node has been disposed
  15354. * @returns true if the node was disposed
  15355. */
  15356. Node.prototype.isDisposed = function () {
  15357. return this._isDisposed;
  15358. };
  15359. Object.defineProperty(Node.prototype, "parent", {
  15360. get: function () {
  15361. return this._parentNode;
  15362. },
  15363. /**
  15364. * Gets or sets the parent of the node
  15365. */
  15366. set: function (parent) {
  15367. if (this._parentNode === parent) {
  15368. return;
  15369. }
  15370. // Remove self from list of children of parent
  15371. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15372. var index = this._parentNode._children.indexOf(this);
  15373. if (index !== -1) {
  15374. this._parentNode._children.splice(index, 1);
  15375. }
  15376. }
  15377. // Store new parent
  15378. this._parentNode = parent;
  15379. // Add as child to new parent
  15380. if (this._parentNode) {
  15381. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15382. this._parentNode._children = new Array();
  15383. }
  15384. this._parentNode._children.push(this);
  15385. }
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. /**
  15391. * Gets a string idenfifying the name of the class
  15392. * @returns "Node" string
  15393. */
  15394. Node.prototype.getClassName = function () {
  15395. return "Node";
  15396. };
  15397. Object.defineProperty(Node.prototype, "onDispose", {
  15398. /**
  15399. * Sets a callback that will be raised when the node will be disposed
  15400. */
  15401. set: function (callback) {
  15402. if (this._onDisposeObserver) {
  15403. this.onDisposeObservable.remove(this._onDisposeObserver);
  15404. }
  15405. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15406. },
  15407. enumerable: true,
  15408. configurable: true
  15409. });
  15410. /**
  15411. * Gets the scene of the node
  15412. * @returns a {BABYLON.Scene}
  15413. */
  15414. Node.prototype.getScene = function () {
  15415. return this._scene;
  15416. };
  15417. /**
  15418. * Gets the engine of the node
  15419. * @returns a {BABYLON.Engine}
  15420. */
  15421. Node.prototype.getEngine = function () {
  15422. return this._scene.getEngine();
  15423. };
  15424. /**
  15425. * Attach a behavior to the node
  15426. * @see http://doc.babylonjs.com/features/behaviour
  15427. * @param behavior defines the behavior to attach
  15428. * @returns the current Node
  15429. */
  15430. Node.prototype.addBehavior = function (behavior) {
  15431. var _this = this;
  15432. var index = this._behaviors.indexOf(behavior);
  15433. if (index !== -1) {
  15434. return this;
  15435. }
  15436. behavior.init();
  15437. if (this._scene.isLoading) {
  15438. // We defer the attach when the scene will be loaded
  15439. var observer = this._scene.onDataLoadedObservable.add(function () {
  15440. behavior.attach(_this);
  15441. setTimeout(function () {
  15442. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15443. _this._scene.onDataLoadedObservable.remove(observer);
  15444. }, 0);
  15445. });
  15446. }
  15447. else {
  15448. behavior.attach(this);
  15449. }
  15450. this._behaviors.push(behavior);
  15451. return this;
  15452. };
  15453. /**
  15454. * Remove an attached behavior
  15455. * @see http://doc.babylonjs.com/features/behaviour
  15456. * @param behavior defines the behavior to attach
  15457. * @returns the current Node
  15458. */
  15459. Node.prototype.removeBehavior = function (behavior) {
  15460. var index = this._behaviors.indexOf(behavior);
  15461. if (index === -1) {
  15462. return this;
  15463. }
  15464. this._behaviors[index].detach();
  15465. this._behaviors.splice(index, 1);
  15466. return this;
  15467. };
  15468. Object.defineProperty(Node.prototype, "behaviors", {
  15469. /**
  15470. * Gets the list of attached behaviors
  15471. * @see http://doc.babylonjs.com/features/behaviour
  15472. */
  15473. get: function () {
  15474. return this._behaviors;
  15475. },
  15476. enumerable: true,
  15477. configurable: true
  15478. });
  15479. /**
  15480. * Gets an attached behavior by name
  15481. * @param name defines the name of the behavior to look for
  15482. * @see http://doc.babylonjs.com/features/behaviour
  15483. * @returns null if behavior was not found else the requested behavior
  15484. */
  15485. Node.prototype.getBehaviorByName = function (name) {
  15486. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15487. var behavior = _a[_i];
  15488. if (behavior.name === name) {
  15489. return behavior;
  15490. }
  15491. }
  15492. return null;
  15493. };
  15494. /**
  15495. * Returns the world matrix of the node
  15496. * @returns a matrix containing the node's world matrix
  15497. */
  15498. Node.prototype.getWorldMatrix = function () {
  15499. return BABYLON.Matrix.Identity();
  15500. };
  15501. // override it in derived class if you add new variables to the cache
  15502. // and call the parent class method
  15503. /** @ignore */
  15504. Node.prototype._initCache = function () {
  15505. this._cache = {};
  15506. this._cache.parent = undefined;
  15507. };
  15508. /** @ignore */
  15509. Node.prototype.updateCache = function (force) {
  15510. if (!force && this.isSynchronized())
  15511. return;
  15512. this._cache.parent = this.parent;
  15513. this._updateCache();
  15514. };
  15515. // override it in derived class if you add new variables to the cache
  15516. // and call the parent class method if !ignoreParentClass
  15517. /** @ignore */
  15518. Node.prototype._updateCache = function (ignoreParentClass) {
  15519. };
  15520. // override it in derived class if you add new variables to the cache
  15521. /** @ignore */
  15522. Node.prototype._isSynchronized = function () {
  15523. return true;
  15524. };
  15525. /** @ignore */
  15526. Node.prototype._markSyncedWithParent = function () {
  15527. if (this.parent) {
  15528. this._parentRenderId = this.parent._currentRenderId;
  15529. }
  15530. };
  15531. /** @ignore */
  15532. Node.prototype.isSynchronizedWithParent = function () {
  15533. if (!this.parent) {
  15534. return true;
  15535. }
  15536. if (this._parentRenderId !== this.parent._currentRenderId) {
  15537. return false;
  15538. }
  15539. return this.parent.isSynchronized();
  15540. };
  15541. /** @ignore */
  15542. Node.prototype.isSynchronized = function (updateCache) {
  15543. var check = this.hasNewParent();
  15544. check = check || !this.isSynchronizedWithParent();
  15545. check = check || !this._isSynchronized();
  15546. if (updateCache)
  15547. this.updateCache(true);
  15548. return !check;
  15549. };
  15550. /** @ignore */
  15551. Node.prototype.hasNewParent = function (update) {
  15552. if (this._cache.parent === this.parent)
  15553. return false;
  15554. if (update)
  15555. this._cache.parent = this.parent;
  15556. return true;
  15557. };
  15558. /**
  15559. * Is this node ready to be used/rendered
  15560. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15561. * @return true if the node is ready
  15562. */
  15563. Node.prototype.isReady = function (completeCheck) {
  15564. if (completeCheck === void 0) { completeCheck = false; }
  15565. return this._isReady;
  15566. };
  15567. /**
  15568. * Is this node enabled?
  15569. * 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
  15570. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15571. * @return whether this node (and its parent) is enabled
  15572. * @see setEnabled
  15573. */
  15574. Node.prototype.isEnabled = function (checkAncestors) {
  15575. if (checkAncestors === void 0) { checkAncestors = true; }
  15576. if (checkAncestors === false) {
  15577. return this._isEnabled;
  15578. }
  15579. if (this._isEnabled === false) {
  15580. return false;
  15581. }
  15582. if (this.parent !== undefined && this.parent !== null) {
  15583. return this.parent.isEnabled(checkAncestors);
  15584. }
  15585. return true;
  15586. };
  15587. /**
  15588. * Set the enabled state of this node
  15589. * @param value defines the new enabled state
  15590. * @see isEnabled
  15591. */
  15592. Node.prototype.setEnabled = function (value) {
  15593. this._isEnabled = value;
  15594. };
  15595. /**
  15596. * Is this node a descendant of the given node?
  15597. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15598. * @param ancestor defines the parent node to inspect
  15599. * @see parent
  15600. * @returns a boolean indicating if this node is a descendant of the given node
  15601. */
  15602. Node.prototype.isDescendantOf = function (ancestor) {
  15603. if (this.parent) {
  15604. if (this.parent === ancestor) {
  15605. return true;
  15606. }
  15607. return this.parent.isDescendantOf(ancestor);
  15608. }
  15609. return false;
  15610. };
  15611. /** @ignore */
  15612. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15613. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15614. if (!this._children) {
  15615. return;
  15616. }
  15617. for (var index = 0; index < this._children.length; index++) {
  15618. var item = this._children[index];
  15619. if (!predicate || predicate(item)) {
  15620. results.push(item);
  15621. }
  15622. if (!directDescendantsOnly) {
  15623. item._getDescendants(results, false, predicate);
  15624. }
  15625. }
  15626. };
  15627. /**
  15628. * Will return all nodes that have this node as ascendant
  15629. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15630. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15631. * @return all children nodes of all types
  15632. */
  15633. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15634. var results = new Array();
  15635. this._getDescendants(results, directDescendantsOnly, predicate);
  15636. return results;
  15637. };
  15638. /**
  15639. * Get all child-meshes of this node
  15640. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15641. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15642. * @returns an array of {BABYLON.AbstractMesh}
  15643. */
  15644. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15645. var results = [];
  15646. this._getDescendants(results, directDescendantsOnly, function (node) {
  15647. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15648. });
  15649. return results;
  15650. };
  15651. /**
  15652. * Get all child-transformNodes of this node
  15653. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15654. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15655. * @returns an array of {BABYLON.TransformNode}
  15656. */
  15657. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15658. var results = [];
  15659. this._getDescendants(results, directDescendantsOnly, function (node) {
  15660. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15661. });
  15662. return results;
  15663. };
  15664. /**
  15665. * Get all direct children of this node
  15666. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15667. * @returns an array of {BABYLON.Node}
  15668. */
  15669. Node.prototype.getChildren = function (predicate) {
  15670. return this.getDescendants(true, predicate);
  15671. };
  15672. /** @ignore */
  15673. Node.prototype._setReady = function (state) {
  15674. if (state === this._isReady) {
  15675. return;
  15676. }
  15677. if (!state) {
  15678. this._isReady = false;
  15679. return;
  15680. }
  15681. this._isReady = true;
  15682. if (this.onReady) {
  15683. this.onReady(this);
  15684. }
  15685. };
  15686. /**
  15687. * Get an animation by name
  15688. * @param name defines the name of the animation to look for
  15689. * @returns null if not found else the requested animation
  15690. */
  15691. Node.prototype.getAnimationByName = function (name) {
  15692. for (var i = 0; i < this.animations.length; i++) {
  15693. var animation = this.animations[i];
  15694. if (animation.name === name) {
  15695. return animation;
  15696. }
  15697. }
  15698. return null;
  15699. };
  15700. /**
  15701. * Creates an animation range for this node
  15702. * @param name defines the name of the range
  15703. * @param from defines the starting key
  15704. * @param to defines the end key
  15705. */
  15706. Node.prototype.createAnimationRange = function (name, from, to) {
  15707. // check name not already in use
  15708. if (!this._ranges[name]) {
  15709. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15710. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15711. if (this.animations[i]) {
  15712. this.animations[i].createRange(name, from, to);
  15713. }
  15714. }
  15715. }
  15716. };
  15717. /**
  15718. * Delete a specific animation range
  15719. * @param name defines the name of the range to delete
  15720. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15721. */
  15722. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15723. if (deleteFrames === void 0) { deleteFrames = true; }
  15724. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15725. if (this.animations[i]) {
  15726. this.animations[i].deleteRange(name, deleteFrames);
  15727. }
  15728. }
  15729. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15730. };
  15731. /**
  15732. * Get an animation range by name
  15733. * @param name defines the name of the animation range to look for
  15734. * @returns null if not found else the requested animation range
  15735. */
  15736. Node.prototype.getAnimationRange = function (name) {
  15737. return this._ranges[name];
  15738. };
  15739. /**
  15740. * Will start the animation sequence
  15741. * @param name defines the range frames for animation sequence
  15742. * @param loop defines if the animation should loop (false by default)
  15743. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15744. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15745. * @returns the object created for this animation. If range does not exist, it will return null
  15746. */
  15747. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15748. var range = this.getAnimationRange(name);
  15749. if (!range) {
  15750. return null;
  15751. }
  15752. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15753. };
  15754. /**
  15755. * Serialize animation ranges into a JSON compatible object
  15756. * @returns serialization object
  15757. */
  15758. Node.prototype.serializeAnimationRanges = function () {
  15759. var serializationRanges = [];
  15760. for (var name in this._ranges) {
  15761. var localRange = this._ranges[name];
  15762. if (!localRange) {
  15763. continue;
  15764. }
  15765. var range = {};
  15766. range.name = name;
  15767. range.from = localRange.from;
  15768. range.to = localRange.to;
  15769. serializationRanges.push(range);
  15770. }
  15771. return serializationRanges;
  15772. };
  15773. /**
  15774. * Computes the world matrix of the node
  15775. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15776. * @returns the world matrix
  15777. */
  15778. Node.prototype.computeWorldMatrix = function (force) {
  15779. return BABYLON.Matrix.Identity();
  15780. };
  15781. /**
  15782. * Releases all associated resources
  15783. */
  15784. Node.prototype.dispose = function () {
  15785. this.parent = null;
  15786. // Callback
  15787. this.onDisposeObservable.notifyObservers(this);
  15788. this.onDisposeObservable.clear();
  15789. // Behaviors
  15790. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15791. var behavior = _a[_i];
  15792. behavior.detach();
  15793. }
  15794. this._behaviors = [];
  15795. this._isDisposed = true;
  15796. };
  15797. /**
  15798. * Parse animation range data from a serialization object and store them into a given node
  15799. * @param node defines where to store the animation ranges
  15800. * @param parsedNode defines the serialization object to read data from
  15801. * @param scene defines the hosting scene
  15802. */
  15803. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15804. if (parsedNode.ranges) {
  15805. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15806. var data = parsedNode.ranges[index];
  15807. node.createAnimationRange(data.name, data.from, data.to);
  15808. }
  15809. }
  15810. };
  15811. __decorate([
  15812. BABYLON.serialize()
  15813. ], Node.prototype, "name", void 0);
  15814. __decorate([
  15815. BABYLON.serialize()
  15816. ], Node.prototype, "id", void 0);
  15817. __decorate([
  15818. BABYLON.serialize()
  15819. ], Node.prototype, "uniqueId", void 0);
  15820. __decorate([
  15821. BABYLON.serialize()
  15822. ], Node.prototype, "state", void 0);
  15823. __decorate([
  15824. BABYLON.serialize()
  15825. ], Node.prototype, "metadata", void 0);
  15826. return Node;
  15827. }());
  15828. BABYLON.Node = Node;
  15829. })(BABYLON || (BABYLON = {}));
  15830. //# sourceMappingURL=babylon.node.js.map
  15831. var BABYLON;
  15832. (function (BABYLON) {
  15833. var BoundingSphere = /** @class */ (function () {
  15834. function BoundingSphere(minimum, maximum) {
  15835. this.minimum = minimum;
  15836. this.maximum = maximum;
  15837. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15838. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15839. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15840. this.radius = distance * 0.5;
  15841. this.centerWorld = BABYLON.Vector3.Zero();
  15842. this._update(BABYLON.Matrix.Identity());
  15843. }
  15844. // Methods
  15845. BoundingSphere.prototype._update = function (world) {
  15846. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15847. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15848. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15849. };
  15850. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15851. for (var i = 0; i < 6; i++) {
  15852. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15853. return false;
  15854. }
  15855. return true;
  15856. };
  15857. BoundingSphere.prototype.intersectsPoint = function (point) {
  15858. var x = this.centerWorld.x - point.x;
  15859. var y = this.centerWorld.y - point.y;
  15860. var z = this.centerWorld.z - point.z;
  15861. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15862. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15863. return false;
  15864. return true;
  15865. };
  15866. // Statics
  15867. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15868. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15869. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15870. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15871. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15872. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15873. return false;
  15874. return true;
  15875. };
  15876. return BoundingSphere;
  15877. }());
  15878. BABYLON.BoundingSphere = BoundingSphere;
  15879. })(BABYLON || (BABYLON = {}));
  15880. //# sourceMappingURL=babylon.boundingSphere.js.map
  15881. var BABYLON;
  15882. (function (BABYLON) {
  15883. var BoundingBox = /** @class */ (function () {
  15884. function BoundingBox(minimum, maximum) {
  15885. this.minimum = minimum;
  15886. this.maximum = maximum;
  15887. this.vectors = new Array();
  15888. this.vectorsWorld = new Array();
  15889. // Bounding vectors
  15890. this.vectors.push(this.minimum.clone());
  15891. this.vectors.push(this.maximum.clone());
  15892. this.vectors.push(this.minimum.clone());
  15893. this.vectors[2].x = this.maximum.x;
  15894. this.vectors.push(this.minimum.clone());
  15895. this.vectors[3].y = this.maximum.y;
  15896. this.vectors.push(this.minimum.clone());
  15897. this.vectors[4].z = this.maximum.z;
  15898. this.vectors.push(this.maximum.clone());
  15899. this.vectors[5].z = this.minimum.z;
  15900. this.vectors.push(this.maximum.clone());
  15901. this.vectors[6].x = this.minimum.x;
  15902. this.vectors.push(this.maximum.clone());
  15903. this.vectors[7].y = this.minimum.y;
  15904. // OBB
  15905. this.center = this.maximum.add(this.minimum).scale(0.5);
  15906. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15907. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15908. // World
  15909. for (var index = 0; index < this.vectors.length; index++) {
  15910. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15911. }
  15912. this.minimumWorld = BABYLON.Vector3.Zero();
  15913. this.maximumWorld = BABYLON.Vector3.Zero();
  15914. this.centerWorld = BABYLON.Vector3.Zero();
  15915. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15916. this._update(BABYLON.Matrix.Identity());
  15917. }
  15918. // Methods
  15919. BoundingBox.prototype.getWorldMatrix = function () {
  15920. return this._worldMatrix;
  15921. };
  15922. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15923. this._worldMatrix.copyFrom(matrix);
  15924. return this;
  15925. };
  15926. BoundingBox.prototype._update = function (world) {
  15927. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15928. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15929. for (var index = 0; index < this.vectors.length; index++) {
  15930. var v = this.vectorsWorld[index];
  15931. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15932. if (v.x < this.minimumWorld.x)
  15933. this.minimumWorld.x = v.x;
  15934. if (v.y < this.minimumWorld.y)
  15935. this.minimumWorld.y = v.y;
  15936. if (v.z < this.minimumWorld.z)
  15937. this.minimumWorld.z = v.z;
  15938. if (v.x > this.maximumWorld.x)
  15939. this.maximumWorld.x = v.x;
  15940. if (v.y > this.maximumWorld.y)
  15941. this.maximumWorld.y = v.y;
  15942. if (v.z > this.maximumWorld.z)
  15943. this.maximumWorld.z = v.z;
  15944. }
  15945. // Extend
  15946. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15947. this.extendSizeWorld.scaleInPlace(0.5);
  15948. // OBB
  15949. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15950. this.centerWorld.scaleInPlace(0.5);
  15951. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15952. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15953. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15954. this._worldMatrix = world;
  15955. };
  15956. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15957. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15958. };
  15959. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15960. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15961. };
  15962. BoundingBox.prototype.intersectsPoint = function (point) {
  15963. var delta = -BABYLON.Epsilon;
  15964. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15965. return false;
  15966. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15967. return false;
  15968. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15969. return false;
  15970. return true;
  15971. };
  15972. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15973. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15974. };
  15975. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15976. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15977. return false;
  15978. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15979. return false;
  15980. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15981. return false;
  15982. return true;
  15983. };
  15984. // Statics
  15985. BoundingBox.Intersects = function (box0, box1) {
  15986. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15987. return false;
  15988. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15989. return false;
  15990. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15991. return false;
  15992. return true;
  15993. };
  15994. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15995. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15996. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15997. return (num <= (sphereRadius * sphereRadius));
  15998. };
  15999. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16000. for (var p = 0; p < 6; p++) {
  16001. for (var i = 0; i < 8; i++) {
  16002. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16003. return false;
  16004. }
  16005. }
  16006. }
  16007. return true;
  16008. };
  16009. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16010. for (var p = 0; p < 6; p++) {
  16011. var inCount = 8;
  16012. for (var i = 0; i < 8; i++) {
  16013. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16014. --inCount;
  16015. }
  16016. else {
  16017. break;
  16018. }
  16019. }
  16020. if (inCount === 0)
  16021. return false;
  16022. }
  16023. return true;
  16024. };
  16025. return BoundingBox;
  16026. }());
  16027. BABYLON.BoundingBox = BoundingBox;
  16028. })(BABYLON || (BABYLON = {}));
  16029. //# sourceMappingURL=babylon.boundingBox.js.map
  16030. var BABYLON;
  16031. (function (BABYLON) {
  16032. var computeBoxExtents = function (axis, box) {
  16033. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16034. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16035. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16036. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16037. var r = r0 + r1 + r2;
  16038. return {
  16039. min: p - r,
  16040. max: p + r
  16041. };
  16042. };
  16043. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16044. var axisOverlap = function (axis, box0, box1) {
  16045. var result0 = computeBoxExtents(axis, box0);
  16046. var result1 = computeBoxExtents(axis, box1);
  16047. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16048. };
  16049. var BoundingInfo = /** @class */ (function () {
  16050. function BoundingInfo(minimum, maximum) {
  16051. this.minimum = minimum;
  16052. this.maximum = maximum;
  16053. this._isLocked = false;
  16054. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16055. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16056. }
  16057. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16058. get: function () {
  16059. return this._isLocked;
  16060. },
  16061. set: function (value) {
  16062. this._isLocked = value;
  16063. },
  16064. enumerable: true,
  16065. configurable: true
  16066. });
  16067. // Methods
  16068. BoundingInfo.prototype.update = function (world) {
  16069. if (this._isLocked) {
  16070. return;
  16071. }
  16072. this.boundingBox._update(world);
  16073. this.boundingSphere._update(world);
  16074. };
  16075. /**
  16076. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16077. * @param center New center of the bounding info
  16078. * @param extend New extend of the bounding info
  16079. */
  16080. BoundingInfo.prototype.centerOn = function (center, extend) {
  16081. this.minimum = center.subtract(extend);
  16082. this.maximum = center.add(extend);
  16083. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16084. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16085. return this;
  16086. };
  16087. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16088. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16089. return false;
  16090. return this.boundingBox.isInFrustum(frustumPlanes);
  16091. };
  16092. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16093. /**
  16094. * Gets the world distance between the min and max points of the bounding box
  16095. */
  16096. get: function () {
  16097. var boundingBox = this.boundingBox;
  16098. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16099. return size.length();
  16100. },
  16101. enumerable: true,
  16102. configurable: true
  16103. });
  16104. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16105. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16106. };
  16107. BoundingInfo.prototype._checkCollision = function (collider) {
  16108. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16109. };
  16110. BoundingInfo.prototype.intersectsPoint = function (point) {
  16111. if (!this.boundingSphere.centerWorld) {
  16112. return false;
  16113. }
  16114. if (!this.boundingSphere.intersectsPoint(point)) {
  16115. return false;
  16116. }
  16117. if (!this.boundingBox.intersectsPoint(point)) {
  16118. return false;
  16119. }
  16120. return true;
  16121. };
  16122. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16123. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16124. return false;
  16125. }
  16126. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16127. return false;
  16128. }
  16129. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16130. return false;
  16131. }
  16132. if (!precise) {
  16133. return true;
  16134. }
  16135. var box0 = this.boundingBox;
  16136. var box1 = boundingInfo.boundingBox;
  16137. if (!axisOverlap(box0.directions[0], box0, box1))
  16138. return false;
  16139. if (!axisOverlap(box0.directions[1], box0, box1))
  16140. return false;
  16141. if (!axisOverlap(box0.directions[2], box0, box1))
  16142. return false;
  16143. if (!axisOverlap(box1.directions[0], box0, box1))
  16144. return false;
  16145. if (!axisOverlap(box1.directions[1], box0, box1))
  16146. return false;
  16147. if (!axisOverlap(box1.directions[2], box0, box1))
  16148. return false;
  16149. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16150. return false;
  16151. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16152. return false;
  16153. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16154. return false;
  16155. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16156. return false;
  16157. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16158. return false;
  16159. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16160. return false;
  16161. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16162. return false;
  16163. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16164. return false;
  16165. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16166. return false;
  16167. return true;
  16168. };
  16169. return BoundingInfo;
  16170. }());
  16171. BABYLON.BoundingInfo = BoundingInfo;
  16172. })(BABYLON || (BABYLON = {}));
  16173. //# sourceMappingURL=babylon.boundingInfo.js.map
  16174. var BABYLON;
  16175. (function (BABYLON) {
  16176. var TransformNode = /** @class */ (function (_super) {
  16177. __extends(TransformNode, _super);
  16178. function TransformNode(name, scene, isPure) {
  16179. if (scene === void 0) { scene = null; }
  16180. if (isPure === void 0) { isPure = true; }
  16181. var _this = _super.call(this, name, scene) || this;
  16182. // Properties
  16183. _this._rotation = BABYLON.Vector3.Zero();
  16184. _this._scaling = BABYLON.Vector3.One();
  16185. _this._isDirty = false;
  16186. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16187. _this.scalingDeterminant = 1;
  16188. _this.infiniteDistance = false;
  16189. _this.position = BABYLON.Vector3.Zero();
  16190. _this._localWorld = BABYLON.Matrix.Zero();
  16191. _this._worldMatrix = BABYLON.Matrix.Zero();
  16192. _this._worldMatrixDeterminant = 0;
  16193. _this._absolutePosition = BABYLON.Vector3.Zero();
  16194. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16195. _this._postMultiplyPivotMatrix = false;
  16196. _this._isWorldMatrixFrozen = false;
  16197. /**
  16198. * An event triggered after the world matrix is updated
  16199. * @type {BABYLON.Observable}
  16200. */
  16201. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16202. _this._nonUniformScaling = false;
  16203. if (isPure) {
  16204. _this.getScene().addTransformNode(_this);
  16205. }
  16206. return _this;
  16207. }
  16208. Object.defineProperty(TransformNode.prototype, "rotation", {
  16209. /**
  16210. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16211. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16212. * Default : (0.0, 0.0, 0.0)
  16213. */
  16214. get: function () {
  16215. return this._rotation;
  16216. },
  16217. set: function (newRotation) {
  16218. this._rotation = newRotation;
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. Object.defineProperty(TransformNode.prototype, "scaling", {
  16224. /**
  16225. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16226. * Default : (1.0, 1.0, 1.0)
  16227. */
  16228. get: function () {
  16229. return this._scaling;
  16230. },
  16231. /**
  16232. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16233. * Default : (1.0, 1.0, 1.0)
  16234. */
  16235. set: function (newScaling) {
  16236. this._scaling = newScaling;
  16237. },
  16238. enumerable: true,
  16239. configurable: true
  16240. });
  16241. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16242. /**
  16243. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16244. * It's null by default.
  16245. * 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)
  16246. */
  16247. get: function () {
  16248. return this._rotationQuaternion;
  16249. },
  16250. set: function (quaternion) {
  16251. this._rotationQuaternion = quaternion;
  16252. //reset the rotation vector.
  16253. if (quaternion && this.rotation.length()) {
  16254. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16255. }
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. /**
  16261. * Returns the latest update of the World matrix
  16262. * Returns a Matrix.
  16263. */
  16264. TransformNode.prototype.getWorldMatrix = function () {
  16265. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16266. this.computeWorldMatrix();
  16267. }
  16268. return this._worldMatrix;
  16269. };
  16270. /**
  16271. * Returns the latest update of the World matrix determinant.
  16272. */
  16273. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16274. return this._worldMatrixDeterminant;
  16275. };
  16276. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16277. /**
  16278. * Returns directly the latest state of the mesh World matrix.
  16279. * A Matrix is returned.
  16280. */
  16281. get: function () {
  16282. return this._worldMatrix;
  16283. },
  16284. enumerable: true,
  16285. configurable: true
  16286. });
  16287. /**
  16288. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16289. * Returns the AbstractMesh.
  16290. */
  16291. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16292. this._poseMatrix.copyFrom(matrix);
  16293. return this;
  16294. };
  16295. /**
  16296. * Returns the mesh Pose matrix.
  16297. * Returned object : Matrix
  16298. */
  16299. TransformNode.prototype.getPoseMatrix = function () {
  16300. return this._poseMatrix;
  16301. };
  16302. TransformNode.prototype._isSynchronized = function () {
  16303. if (this._isDirty) {
  16304. return false;
  16305. }
  16306. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16307. return false;
  16308. if (this._cache.pivotMatrixUpdated) {
  16309. return false;
  16310. }
  16311. if (this.infiniteDistance) {
  16312. return false;
  16313. }
  16314. if (!this._cache.position.equals(this.position))
  16315. return false;
  16316. if (this.rotationQuaternion) {
  16317. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16318. return false;
  16319. }
  16320. if (!this._cache.rotation.equals(this.rotation))
  16321. return false;
  16322. if (!this._cache.scaling.equals(this.scaling))
  16323. return false;
  16324. return true;
  16325. };
  16326. TransformNode.prototype._initCache = function () {
  16327. _super.prototype._initCache.call(this);
  16328. this._cache.localMatrixUpdated = false;
  16329. this._cache.position = BABYLON.Vector3.Zero();
  16330. this._cache.scaling = BABYLON.Vector3.Zero();
  16331. this._cache.rotation = BABYLON.Vector3.Zero();
  16332. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16333. this._cache.billboardMode = -1;
  16334. };
  16335. TransformNode.prototype.markAsDirty = function (property) {
  16336. if (property === "rotation") {
  16337. this.rotationQuaternion = null;
  16338. }
  16339. this._currentRenderId = Number.MAX_VALUE;
  16340. this._isDirty = true;
  16341. return this;
  16342. };
  16343. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16344. /**
  16345. * Returns the current mesh absolute position.
  16346. * Retuns a Vector3.
  16347. */
  16348. get: function () {
  16349. return this._absolutePosition;
  16350. },
  16351. enumerable: true,
  16352. configurable: true
  16353. });
  16354. /**
  16355. * Sets a new matrix to apply before all other transformation
  16356. * @param matrix defines the transform matrix
  16357. * @returns the current TransformNode
  16358. */
  16359. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16360. return this.setPivotMatrix(matrix, false);
  16361. };
  16362. /**
  16363. * Sets a new pivot matrix to the current node
  16364. * @param matrix defines the new pivot matrix to use
  16365. * @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
  16366. * @returns the current TransformNode
  16367. */
  16368. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16369. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16370. this._pivotMatrix = matrix.clone();
  16371. this._cache.pivotMatrixUpdated = true;
  16372. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16373. if (this._postMultiplyPivotMatrix) {
  16374. if (!this._pivotMatrixInverse) {
  16375. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16376. }
  16377. else {
  16378. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16379. }
  16380. }
  16381. return this;
  16382. };
  16383. /**
  16384. * Returns the mesh pivot matrix.
  16385. * Default : Identity.
  16386. * A Matrix is returned.
  16387. */
  16388. TransformNode.prototype.getPivotMatrix = function () {
  16389. return this._pivotMatrix;
  16390. };
  16391. /**
  16392. * Prevents the World matrix to be computed any longer.
  16393. * Returns the AbstractMesh.
  16394. */
  16395. TransformNode.prototype.freezeWorldMatrix = function () {
  16396. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16397. this.computeWorldMatrix(true);
  16398. this._isWorldMatrixFrozen = true;
  16399. return this;
  16400. };
  16401. /**
  16402. * Allows back the World matrix computation.
  16403. * Returns the AbstractMesh.
  16404. */
  16405. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16406. this._isWorldMatrixFrozen = false;
  16407. this.computeWorldMatrix(true);
  16408. return this;
  16409. };
  16410. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16411. /**
  16412. * True if the World matrix has been frozen.
  16413. * Returns a boolean.
  16414. */
  16415. get: function () {
  16416. return this._isWorldMatrixFrozen;
  16417. },
  16418. enumerable: true,
  16419. configurable: true
  16420. });
  16421. /**
  16422. * Retuns the mesh absolute position in the World.
  16423. * Returns a Vector3.
  16424. */
  16425. TransformNode.prototype.getAbsolutePosition = function () {
  16426. this.computeWorldMatrix();
  16427. return this._absolutePosition;
  16428. };
  16429. /**
  16430. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16431. * Returns the AbstractMesh.
  16432. */
  16433. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16434. if (!absolutePosition) {
  16435. return this;
  16436. }
  16437. var absolutePositionX;
  16438. var absolutePositionY;
  16439. var absolutePositionZ;
  16440. if (absolutePosition.x === undefined) {
  16441. if (arguments.length < 3) {
  16442. return this;
  16443. }
  16444. absolutePositionX = arguments[0];
  16445. absolutePositionY = arguments[1];
  16446. absolutePositionZ = arguments[2];
  16447. }
  16448. else {
  16449. absolutePositionX = absolutePosition.x;
  16450. absolutePositionY = absolutePosition.y;
  16451. absolutePositionZ = absolutePosition.z;
  16452. }
  16453. if (this.parent) {
  16454. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16455. invertParentWorldMatrix.invert();
  16456. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16457. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16458. }
  16459. else {
  16460. this.position.x = absolutePositionX;
  16461. this.position.y = absolutePositionY;
  16462. this.position.z = absolutePositionZ;
  16463. }
  16464. return this;
  16465. };
  16466. /**
  16467. * Sets the mesh position in its local space.
  16468. * Returns the AbstractMesh.
  16469. */
  16470. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16471. this.computeWorldMatrix();
  16472. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16473. return this;
  16474. };
  16475. /**
  16476. * Returns the mesh position in the local space from the current World matrix values.
  16477. * Returns a new Vector3.
  16478. */
  16479. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16480. this.computeWorldMatrix();
  16481. var invLocalWorldMatrix = this._localWorld.clone();
  16482. invLocalWorldMatrix.invert();
  16483. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16484. };
  16485. /**
  16486. * Translates the mesh along the passed Vector3 in its local space.
  16487. * Returns the AbstractMesh.
  16488. */
  16489. TransformNode.prototype.locallyTranslate = function (vector3) {
  16490. this.computeWorldMatrix(true);
  16491. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16492. return this;
  16493. };
  16494. /**
  16495. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16496. * @param targetPoint the position (must be in same space as current mesh) to look at
  16497. * @param yawCor optional yaw (y-axis) correction in radians
  16498. * @param pitchCor optional pitch (x-axis) correction in radians
  16499. * @param rollCor optional roll (z-axis) correction in radians
  16500. * @param space the choosen space of the target
  16501. * @returns the TransformNode.
  16502. */
  16503. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16504. if (yawCor === void 0) { yawCor = 0; }
  16505. if (pitchCor === void 0) { pitchCor = 0; }
  16506. if (rollCor === void 0) { rollCor = 0; }
  16507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16508. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16509. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16510. targetPoint.subtractToRef(pos, dv);
  16511. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16512. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16513. var pitch = Math.atan2(dv.y, len);
  16514. if (this.rotationQuaternion) {
  16515. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16516. }
  16517. else {
  16518. this.rotation.x = pitch + pitchCor;
  16519. this.rotation.y = yaw + yawCor;
  16520. this.rotation.z = rollCor;
  16521. }
  16522. return this;
  16523. };
  16524. /**
  16525. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16526. * This Vector3 is expressed in the World space.
  16527. */
  16528. TransformNode.prototype.getDirection = function (localAxis) {
  16529. var result = BABYLON.Vector3.Zero();
  16530. this.getDirectionToRef(localAxis, result);
  16531. return result;
  16532. };
  16533. /**
  16534. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16535. * localAxis is expressed in the mesh local space.
  16536. * result is computed in the Wordl space from the mesh World matrix.
  16537. * Returns the AbstractMesh.
  16538. */
  16539. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16540. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16541. return this;
  16542. };
  16543. /**
  16544. * Sets a new pivot point to the current node
  16545. * @param point defines the new pivot point to use
  16546. * @param space defines if the point is in world or local space (local by default)
  16547. * @returns the current TransformNode
  16548. */
  16549. TransformNode.prototype.setPivotPoint = function (point, space) {
  16550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16551. if (this.getScene().getRenderId() == 0) {
  16552. this.computeWorldMatrix(true);
  16553. }
  16554. var wm = this.getWorldMatrix();
  16555. if (space == BABYLON.Space.WORLD) {
  16556. var tmat = BABYLON.Tmp.Matrix[0];
  16557. wm.invertToRef(tmat);
  16558. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16559. }
  16560. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16561. };
  16562. /**
  16563. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16564. */
  16565. TransformNode.prototype.getPivotPoint = function () {
  16566. var point = BABYLON.Vector3.Zero();
  16567. this.getPivotPointToRef(point);
  16568. return point;
  16569. };
  16570. /**
  16571. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16572. * Returns the AbstractMesh.
  16573. */
  16574. TransformNode.prototype.getPivotPointToRef = function (result) {
  16575. result.x = -this._pivotMatrix.m[12];
  16576. result.y = -this._pivotMatrix.m[13];
  16577. result.z = -this._pivotMatrix.m[14];
  16578. return this;
  16579. };
  16580. /**
  16581. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16582. */
  16583. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16584. var point = BABYLON.Vector3.Zero();
  16585. this.getAbsolutePivotPointToRef(point);
  16586. return point;
  16587. };
  16588. /**
  16589. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16590. * Returns the AbstractMesh.
  16591. */
  16592. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16593. result.x = this._pivotMatrix.m[12];
  16594. result.y = this._pivotMatrix.m[13];
  16595. result.z = this._pivotMatrix.m[14];
  16596. this.getPivotPointToRef(result);
  16597. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16598. return this;
  16599. };
  16600. /**
  16601. * Defines the passed node as the parent of the current node.
  16602. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16603. * Returns the TransformNode.
  16604. */
  16605. TransformNode.prototype.setParent = function (node) {
  16606. if (node === null) {
  16607. var rotation = BABYLON.Tmp.Quaternion[0];
  16608. var position = BABYLON.Tmp.Vector3[0];
  16609. var scale = BABYLON.Tmp.Vector3[1];
  16610. if (this.parent && this.parent.computeWorldMatrix) {
  16611. this.parent.computeWorldMatrix(true);
  16612. }
  16613. this.computeWorldMatrix(true);
  16614. this.getWorldMatrix().decompose(scale, rotation, position);
  16615. if (this.rotationQuaternion) {
  16616. this.rotationQuaternion.copyFrom(rotation);
  16617. }
  16618. else {
  16619. rotation.toEulerAnglesToRef(this.rotation);
  16620. }
  16621. this.scaling.x = scale.x;
  16622. this.scaling.y = scale.y;
  16623. this.scaling.z = scale.z;
  16624. this.position.x = position.x;
  16625. this.position.y = position.y;
  16626. this.position.z = position.z;
  16627. }
  16628. else {
  16629. var rotation = BABYLON.Tmp.Quaternion[0];
  16630. var position = BABYLON.Tmp.Vector3[0];
  16631. var scale = BABYLON.Tmp.Vector3[1];
  16632. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16633. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16634. this.computeWorldMatrix(true);
  16635. node.computeWorldMatrix(true);
  16636. node.getWorldMatrix().invertToRef(invParentMatrix);
  16637. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16638. diffMatrix.decompose(scale, rotation, position);
  16639. if (this.rotationQuaternion) {
  16640. this.rotationQuaternion.copyFrom(rotation);
  16641. }
  16642. else {
  16643. rotation.toEulerAnglesToRef(this.rotation);
  16644. }
  16645. this.position.x = position.x;
  16646. this.position.y = position.y;
  16647. this.position.z = position.z;
  16648. this.scaling.x = scale.x;
  16649. this.scaling.y = scale.y;
  16650. this.scaling.z = scale.z;
  16651. }
  16652. this.parent = node;
  16653. return this;
  16654. };
  16655. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16656. get: function () {
  16657. return this._nonUniformScaling;
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16663. if (this._nonUniformScaling === value) {
  16664. return false;
  16665. }
  16666. this._nonUniformScaling = true;
  16667. return true;
  16668. };
  16669. /**
  16670. * Attach the current TransformNode to another TransformNode associated with a bone
  16671. * @param bone Bone affecting the TransformNode
  16672. * @param affectedTransformNode TransformNode associated with the bone
  16673. */
  16674. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16675. this._transformToBoneReferal = affectedTransformNode;
  16676. this.parent = bone;
  16677. if (bone.getWorldMatrix().determinant() < 0) {
  16678. this.scalingDeterminant *= -1;
  16679. }
  16680. return this;
  16681. };
  16682. TransformNode.prototype.detachFromBone = function () {
  16683. if (!this.parent) {
  16684. return this;
  16685. }
  16686. if (this.parent.getWorldMatrix().determinant() < 0) {
  16687. this.scalingDeterminant *= -1;
  16688. }
  16689. this._transformToBoneReferal = null;
  16690. this.parent = null;
  16691. return this;
  16692. };
  16693. /**
  16694. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16695. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16696. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16697. * The passed axis is also normalized.
  16698. * Returns the AbstractMesh.
  16699. */
  16700. TransformNode.prototype.rotate = function (axis, amount, space) {
  16701. axis.normalize();
  16702. if (!this.rotationQuaternion) {
  16703. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16704. this.rotation = BABYLON.Vector3.Zero();
  16705. }
  16706. var rotationQuaternion;
  16707. if (!space || space === BABYLON.Space.LOCAL) {
  16708. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16709. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16710. }
  16711. else {
  16712. if (this.parent) {
  16713. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16714. invertParentWorldMatrix.invert();
  16715. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16716. }
  16717. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16718. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16719. }
  16720. return this;
  16721. };
  16722. /**
  16723. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16724. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16725. * The passed axis is also normalized.
  16726. * Returns the AbstractMesh.
  16727. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16728. */
  16729. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16730. axis.normalize();
  16731. if (!this.rotationQuaternion) {
  16732. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16733. this.rotation.copyFromFloats(0, 0, 0);
  16734. }
  16735. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16736. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16737. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16738. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16739. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16740. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16741. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16742. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16743. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16744. return this;
  16745. };
  16746. /**
  16747. * Translates the mesh along the axis vector for the passed distance in the given space.
  16748. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16749. * Returns the AbstractMesh.
  16750. */
  16751. TransformNode.prototype.translate = function (axis, distance, space) {
  16752. var displacementVector = axis.scale(distance);
  16753. if (!space || space === BABYLON.Space.LOCAL) {
  16754. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16755. this.setPositionWithLocalVector(tempV3);
  16756. }
  16757. else {
  16758. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Adds a rotation step to the mesh current rotation.
  16764. * x, y, z are Euler angles expressed in radians.
  16765. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16766. * This means this rotation is made in the mesh local space only.
  16767. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16768. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16769. * ```javascript
  16770. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16771. * ```
  16772. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16773. * 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.
  16774. * Returns the AbstractMesh.
  16775. */
  16776. TransformNode.prototype.addRotation = function (x, y, z) {
  16777. var rotationQuaternion;
  16778. if (this.rotationQuaternion) {
  16779. rotationQuaternion = this.rotationQuaternion;
  16780. }
  16781. else {
  16782. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16783. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16784. }
  16785. var accumulation = BABYLON.Tmp.Quaternion[0];
  16786. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16787. rotationQuaternion.multiplyInPlace(accumulation);
  16788. if (!this.rotationQuaternion) {
  16789. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16790. }
  16791. return this;
  16792. };
  16793. /**
  16794. * Computes the mesh World matrix and returns it.
  16795. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16796. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16797. * If the parameter `force`is set to `true`, the actual computation is done.
  16798. * Returns the mesh World Matrix.
  16799. */
  16800. TransformNode.prototype.computeWorldMatrix = function (force) {
  16801. if (this._isWorldMatrixFrozen) {
  16802. return this._worldMatrix;
  16803. }
  16804. if (!force && this.isSynchronized(true)) {
  16805. return this._worldMatrix;
  16806. }
  16807. this._cache.position.copyFrom(this.position);
  16808. this._cache.scaling.copyFrom(this.scaling);
  16809. this._cache.pivotMatrixUpdated = false;
  16810. this._cache.billboardMode = this.billboardMode;
  16811. this._currentRenderId = this.getScene().getRenderId();
  16812. this._isDirty = false;
  16813. // Scaling
  16814. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16815. // Rotation
  16816. //rotate, if quaternion is set and rotation was used
  16817. if (this.rotationQuaternion) {
  16818. var len = this.rotation.length();
  16819. if (len) {
  16820. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16821. this.rotation.copyFromFloats(0, 0, 0);
  16822. }
  16823. }
  16824. if (this.rotationQuaternion) {
  16825. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16826. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16827. }
  16828. else {
  16829. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16830. this._cache.rotation.copyFrom(this.rotation);
  16831. }
  16832. // Translation
  16833. var camera = this.getScene().activeCamera;
  16834. if (this.infiniteDistance && !this.parent && camera) {
  16835. var cameraWorldMatrix = camera.getWorldMatrix();
  16836. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16837. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16838. }
  16839. else {
  16840. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16841. }
  16842. // Composing transformations
  16843. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16844. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16845. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16846. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16847. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16848. // Need to decompose each rotation here
  16849. var currentPosition = BABYLON.Tmp.Vector3[3];
  16850. if (this.parent && this.parent.getWorldMatrix) {
  16851. if (this._transformToBoneReferal) {
  16852. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16853. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16854. }
  16855. else {
  16856. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16857. }
  16858. }
  16859. else {
  16860. currentPosition.copyFrom(this.position);
  16861. }
  16862. currentPosition.subtractInPlace(camera.globalPosition);
  16863. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16864. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16865. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16866. }
  16867. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16868. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16869. }
  16870. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16871. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16872. }
  16873. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16874. }
  16875. else {
  16876. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16877. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16878. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16879. }
  16880. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16881. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16882. }
  16883. // Local world
  16884. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16885. // Parent
  16886. if (this.parent && this.parent.getWorldMatrix) {
  16887. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16888. if (this._transformToBoneReferal) {
  16889. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16890. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16891. }
  16892. else {
  16893. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16894. }
  16895. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16896. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16897. this._worldMatrix.copyFrom(this._localWorld);
  16898. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16899. }
  16900. else {
  16901. if (this._transformToBoneReferal) {
  16902. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16903. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16904. }
  16905. else {
  16906. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16907. }
  16908. }
  16909. this._markSyncedWithParent();
  16910. }
  16911. else {
  16912. this._worldMatrix.copyFrom(this._localWorld);
  16913. }
  16914. // Post multiply inverse of pivotMatrix
  16915. if (this._postMultiplyPivotMatrix) {
  16916. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16917. }
  16918. // Normal matrix
  16919. if (this.scaling.isNonUniform) {
  16920. this._updateNonUniformScalingState(true);
  16921. }
  16922. else if (this.parent && this.parent._nonUniformScaling) {
  16923. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16924. }
  16925. else {
  16926. this._updateNonUniformScalingState(false);
  16927. }
  16928. this._afterComputeWorldMatrix();
  16929. // Absolute position
  16930. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16931. // Callbacks
  16932. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16933. if (!this._poseMatrix) {
  16934. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16935. }
  16936. // Cache the determinant
  16937. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16938. return this._worldMatrix;
  16939. };
  16940. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16941. };
  16942. /**
  16943. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16944. * @param func: callback function to add
  16945. *
  16946. * Returns the TransformNode.
  16947. */
  16948. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16949. this.onAfterWorldMatrixUpdateObservable.add(func);
  16950. return this;
  16951. };
  16952. /**
  16953. * Removes a registered callback function.
  16954. * Returns the TransformNode.
  16955. */
  16956. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16957. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16958. return this;
  16959. };
  16960. /**
  16961. * Clone the current transform node
  16962. * Returns the new transform node
  16963. * @param name Name of the new clone
  16964. * @param newParent New parent for the clone
  16965. * @param doNotCloneChildren Do not clone children hierarchy
  16966. */
  16967. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16968. var _this = this;
  16969. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16970. result.name = name;
  16971. result.id = name;
  16972. if (newParent) {
  16973. result.parent = newParent;
  16974. }
  16975. if (!doNotCloneChildren) {
  16976. // Children
  16977. var directDescendants = this.getDescendants(true);
  16978. for (var index = 0; index < directDescendants.length; index++) {
  16979. var child = directDescendants[index];
  16980. if (child.clone) {
  16981. child.clone(name + "." + child.name, result);
  16982. }
  16983. }
  16984. }
  16985. return result;
  16986. };
  16987. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16988. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16989. serializationObject.type = this.getClassName();
  16990. // Parent
  16991. if (this.parent) {
  16992. serializationObject.parentId = this.parent.id;
  16993. }
  16994. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16995. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16996. }
  16997. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16998. serializationObject.isEnabled = this.isEnabled();
  16999. // Parent
  17000. if (this.parent) {
  17001. serializationObject.parentId = this.parent.id;
  17002. }
  17003. return serializationObject;
  17004. };
  17005. // Statics
  17006. /**
  17007. * Returns a new TransformNode object parsed from the source provided.
  17008. * The parameter `parsedMesh` is the source.
  17009. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17010. */
  17011. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17012. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17013. if (BABYLON.Tags) {
  17014. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17015. }
  17016. if (parsedTransformNode.localMatrix) {
  17017. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17018. }
  17019. else if (parsedTransformNode.pivotMatrix) {
  17020. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17021. }
  17022. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17023. // Parent
  17024. if (parsedTransformNode.parentId) {
  17025. transformNode._waitingParentId = parsedTransformNode.parentId;
  17026. }
  17027. return transformNode;
  17028. };
  17029. /**
  17030. * Disposes the TransformNode.
  17031. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17032. * Returns nothing.
  17033. */
  17034. TransformNode.prototype.dispose = function (doNotRecurse) {
  17035. // Animations
  17036. this.getScene().stopAnimation(this);
  17037. // Remove from scene
  17038. this.getScene().removeTransformNode(this);
  17039. if (!doNotRecurse) {
  17040. // Children
  17041. var objects = this.getDescendants(true);
  17042. for (var index = 0; index < objects.length; index++) {
  17043. objects[index].dispose();
  17044. }
  17045. }
  17046. else {
  17047. var childMeshes = this.getChildMeshes(true);
  17048. for (index = 0; index < childMeshes.length; index++) {
  17049. var child = childMeshes[index];
  17050. child.parent = null;
  17051. child.computeWorldMatrix(true);
  17052. }
  17053. }
  17054. this.onAfterWorldMatrixUpdateObservable.clear();
  17055. _super.prototype.dispose.call(this);
  17056. };
  17057. // Statics
  17058. TransformNode.BILLBOARDMODE_NONE = 0;
  17059. TransformNode.BILLBOARDMODE_X = 1;
  17060. TransformNode.BILLBOARDMODE_Y = 2;
  17061. TransformNode.BILLBOARDMODE_Z = 4;
  17062. TransformNode.BILLBOARDMODE_ALL = 7;
  17063. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17064. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17065. __decorate([
  17066. BABYLON.serializeAsVector3()
  17067. ], TransformNode.prototype, "_rotation", void 0);
  17068. __decorate([
  17069. BABYLON.serializeAsQuaternion()
  17070. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17071. __decorate([
  17072. BABYLON.serializeAsVector3()
  17073. ], TransformNode.prototype, "_scaling", void 0);
  17074. __decorate([
  17075. BABYLON.serialize()
  17076. ], TransformNode.prototype, "billboardMode", void 0);
  17077. __decorate([
  17078. BABYLON.serialize()
  17079. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17080. __decorate([
  17081. BABYLON.serialize()
  17082. ], TransformNode.prototype, "infiniteDistance", void 0);
  17083. __decorate([
  17084. BABYLON.serializeAsVector3()
  17085. ], TransformNode.prototype, "position", void 0);
  17086. return TransformNode;
  17087. }(BABYLON.Node));
  17088. BABYLON.TransformNode = TransformNode;
  17089. })(BABYLON || (BABYLON = {}));
  17090. //# sourceMappingURL=babylon.transformNode.js.map
  17091. var BABYLON;
  17092. (function (BABYLON) {
  17093. var AbstractMesh = /** @class */ (function (_super) {
  17094. __extends(AbstractMesh, _super);
  17095. // Constructor
  17096. function AbstractMesh(name, scene) {
  17097. if (scene === void 0) { scene = null; }
  17098. var _this = _super.call(this, name, scene, false) || this;
  17099. _this._facetNb = 0; // facet number
  17100. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17101. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17102. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17103. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17104. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17105. _this._subDiv = {
  17106. max: 1,
  17107. X: 1,
  17108. Y: 1,
  17109. Z: 1
  17110. };
  17111. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17112. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17113. // Events
  17114. /**
  17115. * An event triggered when this mesh collides with another one
  17116. * @type {BABYLON.Observable}
  17117. */
  17118. _this.onCollideObservable = new BABYLON.Observable();
  17119. /**
  17120. * An event triggered when the collision's position changes
  17121. * @type {BABYLON.Observable}
  17122. */
  17123. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17124. /**
  17125. * An event triggered when material is changed
  17126. * @type {BABYLON.Observable}
  17127. */
  17128. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17129. // Properties
  17130. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17131. /**
  17132. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17133. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17134. * or
  17135. * 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.
  17136. * for more info check WebGl documentations
  17137. */
  17138. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17139. /**
  17140. * 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:
  17141. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17142. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17143. * 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.
  17144. */
  17145. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17146. /**
  17147. * 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.
  17148. * The default value is -1 which means don't break the query and wait till the result.
  17149. */
  17150. _this.occlusionRetryCount = -1;
  17151. _this._occlusionInternalRetryCounter = 0;
  17152. _this._isOccluded = false;
  17153. _this._isOcclusionQueryInProgress = false;
  17154. _this._visibility = 1.0;
  17155. _this.alphaIndex = Number.MAX_VALUE;
  17156. _this.isVisible = true;
  17157. _this.isPickable = true;
  17158. _this.showBoundingBox = false;
  17159. _this.showSubMeshesBoundingBox = false;
  17160. _this.isBlocker = false;
  17161. _this.enablePointerMoveEvents = false;
  17162. _this.renderingGroupId = 0;
  17163. _this._receiveShadows = false;
  17164. _this.renderOutline = false;
  17165. _this.outlineColor = BABYLON.Color3.Red();
  17166. _this.outlineWidth = 0.02;
  17167. _this.renderOverlay = false;
  17168. _this.overlayColor = BABYLON.Color3.Red();
  17169. _this.overlayAlpha = 0.5;
  17170. _this._hasVertexAlpha = false;
  17171. _this._useVertexColors = true;
  17172. _this._computeBonesUsingShaders = true;
  17173. _this._numBoneInfluencers = 4;
  17174. _this._applyFog = true;
  17175. _this.useOctreeForRenderingSelection = true;
  17176. _this.useOctreeForPicking = true;
  17177. _this.useOctreeForCollisions = true;
  17178. _this._layerMask = 0x0FFFFFFF;
  17179. /**
  17180. * True if the mesh must be rendered in any case.
  17181. */
  17182. _this.alwaysSelectAsActiveMesh = false;
  17183. /**
  17184. * This scene's action manager
  17185. * @type {BABYLON.ActionManager}
  17186. */
  17187. _this.actionManager = null;
  17188. // Physics
  17189. _this.physicsImpostor = null;
  17190. // Collisions
  17191. _this._checkCollisions = false;
  17192. _this._collisionMask = -1;
  17193. _this._collisionGroup = -1;
  17194. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17195. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17196. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17197. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17198. // Edges
  17199. _this.edgesWidth = 1;
  17200. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17201. // Cache
  17202. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17203. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17204. _this._renderId = 0;
  17205. _this._intersectionsInProgress = new Array();
  17206. _this._unIndexed = false;
  17207. _this._lightSources = new Array();
  17208. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17209. if (collidedMesh === void 0) { collidedMesh = null; }
  17210. //TODO move this to the collision coordinator!
  17211. if (_this.getScene().workerCollisions)
  17212. newPosition.multiplyInPlace(_this._collider._radius);
  17213. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17214. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17215. _this.position.addInPlace(_this._diffPositionForCollisions);
  17216. }
  17217. if (collidedMesh) {
  17218. _this.onCollideObservable.notifyObservers(collidedMesh);
  17219. }
  17220. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17221. };
  17222. _this.getScene().addMesh(_this);
  17223. _this._resyncLightSources();
  17224. return _this;
  17225. }
  17226. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17227. get: function () {
  17228. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17229. },
  17230. enumerable: true,
  17231. configurable: true
  17232. });
  17233. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17234. get: function () {
  17235. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17236. },
  17237. enumerable: true,
  17238. configurable: true
  17239. });
  17240. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17241. get: function () {
  17242. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17248. get: function () {
  17249. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17250. },
  17251. enumerable: true,
  17252. configurable: true
  17253. });
  17254. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17255. get: function () {
  17256. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17257. },
  17258. enumerable: true,
  17259. configurable: true
  17260. });
  17261. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17262. /**
  17263. * Read-only : the number of facets in the mesh
  17264. */
  17265. get: function () {
  17266. return this._facetNb;
  17267. },
  17268. enumerable: true,
  17269. configurable: true
  17270. });
  17271. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17272. /**
  17273. * The number (integer) of subdivisions per axis in the partioning space
  17274. */
  17275. get: function () {
  17276. return this._partitioningSubdivisions;
  17277. },
  17278. set: function (nb) {
  17279. this._partitioningSubdivisions = nb;
  17280. },
  17281. enumerable: true,
  17282. configurable: true
  17283. });
  17284. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17285. /**
  17286. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17287. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17288. */
  17289. get: function () {
  17290. return this._partitioningBBoxRatio;
  17291. },
  17292. set: function (ratio) {
  17293. this._partitioningBBoxRatio = ratio;
  17294. },
  17295. enumerable: true,
  17296. configurable: true
  17297. });
  17298. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17299. /**
  17300. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17301. * Works only for updatable meshes.
  17302. * Doesn't work with multi-materials.
  17303. */
  17304. get: function () {
  17305. return this._facetDepthSort;
  17306. },
  17307. set: function (sort) {
  17308. this._facetDepthSort = sort;
  17309. },
  17310. enumerable: true,
  17311. configurable: true
  17312. });
  17313. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17314. /**
  17315. * The location (Vector3) where the facet depth sort must be computed from.
  17316. * By default, the active camera position.
  17317. * Used only when facet depth sort is enabled.
  17318. */
  17319. get: function () {
  17320. return this._facetDepthSortFrom;
  17321. },
  17322. set: function (location) {
  17323. this._facetDepthSortFrom = location;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17329. /**
  17330. * Read-only boolean : is the feature facetData enabled ?
  17331. */
  17332. get: function () {
  17333. return this._facetDataEnabled;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17339. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17340. return false;
  17341. }
  17342. this._markSubMeshesAsMiscDirty();
  17343. return true;
  17344. };
  17345. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17346. set: function (callback) {
  17347. if (this._onCollideObserver) {
  17348. this.onCollideObservable.remove(this._onCollideObserver);
  17349. }
  17350. this._onCollideObserver = this.onCollideObservable.add(callback);
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17356. set: function (callback) {
  17357. if (this._onCollisionPositionChangeObserver) {
  17358. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17359. }
  17360. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17366. /**
  17367. * 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.
  17368. */
  17369. get: function () {
  17370. return this._isOccluded;
  17371. },
  17372. set: function (value) {
  17373. this._isOccluded = value;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17379. /**
  17380. * Flag to check the progress status of the query
  17381. */
  17382. get: function () {
  17383. return this._isOcclusionQueryInProgress;
  17384. },
  17385. enumerable: true,
  17386. configurable: true
  17387. });
  17388. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17389. /**
  17390. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17391. */
  17392. get: function () {
  17393. return this._visibility;
  17394. },
  17395. /**
  17396. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17397. */
  17398. set: function (value) {
  17399. if (this._visibility === value) {
  17400. return;
  17401. }
  17402. this._visibility = value;
  17403. this._markSubMeshesAsMiscDirty();
  17404. },
  17405. enumerable: true,
  17406. configurable: true
  17407. });
  17408. Object.defineProperty(AbstractMesh.prototype, "material", {
  17409. get: function () {
  17410. return this._material;
  17411. },
  17412. set: function (value) {
  17413. if (this._material === value) {
  17414. return;
  17415. }
  17416. this._material = value;
  17417. if (this.onMaterialChangedObservable.hasObservers) {
  17418. this.onMaterialChangedObservable.notifyObservers(this);
  17419. }
  17420. if (!this.subMeshes) {
  17421. return;
  17422. }
  17423. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17424. var subMesh = _a[_i];
  17425. subMesh.setEffect(null);
  17426. }
  17427. },
  17428. enumerable: true,
  17429. configurable: true
  17430. });
  17431. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17432. get: function () {
  17433. return this._receiveShadows;
  17434. },
  17435. set: function (value) {
  17436. if (this._receiveShadows === value) {
  17437. return;
  17438. }
  17439. this._receiveShadows = value;
  17440. this._markSubMeshesAsLightDirty();
  17441. },
  17442. enumerable: true,
  17443. configurable: true
  17444. });
  17445. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17446. get: function () {
  17447. return this._hasVertexAlpha;
  17448. },
  17449. set: function (value) {
  17450. if (this._hasVertexAlpha === value) {
  17451. return;
  17452. }
  17453. this._hasVertexAlpha = value;
  17454. this._markSubMeshesAsAttributesDirty();
  17455. this._markSubMeshesAsMiscDirty();
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17461. get: function () {
  17462. return this._useVertexColors;
  17463. },
  17464. set: function (value) {
  17465. if (this._useVertexColors === value) {
  17466. return;
  17467. }
  17468. this._useVertexColors = value;
  17469. this._markSubMeshesAsAttributesDirty();
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17475. get: function () {
  17476. return this._computeBonesUsingShaders;
  17477. },
  17478. set: function (value) {
  17479. if (this._computeBonesUsingShaders === value) {
  17480. return;
  17481. }
  17482. this._computeBonesUsingShaders = value;
  17483. this._markSubMeshesAsAttributesDirty();
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17489. get: function () {
  17490. return this._numBoneInfluencers;
  17491. },
  17492. set: function (value) {
  17493. if (this._numBoneInfluencers === value) {
  17494. return;
  17495. }
  17496. this._numBoneInfluencers = value;
  17497. this._markSubMeshesAsAttributesDirty();
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17503. get: function () {
  17504. return this._applyFog;
  17505. },
  17506. set: function (value) {
  17507. if (this._applyFog === value) {
  17508. return;
  17509. }
  17510. this._applyFog = value;
  17511. this._markSubMeshesAsMiscDirty();
  17512. },
  17513. enumerable: true,
  17514. configurable: true
  17515. });
  17516. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17517. get: function () {
  17518. return this._layerMask;
  17519. },
  17520. set: function (value) {
  17521. if (value === this._layerMask) {
  17522. return;
  17523. }
  17524. this._layerMask = value;
  17525. this._resyncLightSources();
  17526. },
  17527. enumerable: true,
  17528. configurable: true
  17529. });
  17530. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17531. get: function () {
  17532. return this._collisionMask;
  17533. },
  17534. set: function (mask) {
  17535. this._collisionMask = !isNaN(mask) ? mask : -1;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17541. get: function () {
  17542. return this._collisionGroup;
  17543. },
  17544. set: function (mask) {
  17545. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17546. },
  17547. enumerable: true,
  17548. configurable: true
  17549. });
  17550. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17551. get: function () {
  17552. return null;
  17553. },
  17554. enumerable: true,
  17555. configurable: true
  17556. });
  17557. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17558. get: function () {
  17559. return this._skeleton;
  17560. },
  17561. set: function (value) {
  17562. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17563. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17564. }
  17565. if (value && value.needInitialSkinMatrix) {
  17566. value._registerMeshWithPoseMatrix(this);
  17567. }
  17568. this._skeleton = value;
  17569. if (!this._skeleton) {
  17570. this._bonesTransformMatrices = null;
  17571. }
  17572. this._markSubMeshesAsAttributesDirty();
  17573. },
  17574. enumerable: true,
  17575. configurable: true
  17576. });
  17577. /**
  17578. * Returns the string "AbstractMesh"
  17579. */
  17580. AbstractMesh.prototype.getClassName = function () {
  17581. return "AbstractMesh";
  17582. };
  17583. /**
  17584. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17585. */
  17586. AbstractMesh.prototype.toString = function (fullDetails) {
  17587. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17588. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17589. if (this._skeleton) {
  17590. ret += ", skeleton: " + this._skeleton.name;
  17591. }
  17592. if (fullDetails) {
  17593. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17594. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17595. }
  17596. return ret;
  17597. };
  17598. AbstractMesh.prototype._rebuild = function () {
  17599. if (this._occlusionQuery) {
  17600. this._occlusionQuery = null;
  17601. }
  17602. if (this._edgesRenderer) {
  17603. this._edgesRenderer._rebuild();
  17604. }
  17605. if (!this.subMeshes) {
  17606. return;
  17607. }
  17608. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17609. var subMesh = _a[_i];
  17610. subMesh._rebuild();
  17611. }
  17612. };
  17613. AbstractMesh.prototype._resyncLightSources = function () {
  17614. this._lightSources.length = 0;
  17615. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17616. var light = _a[_i];
  17617. if (!light.isEnabled()) {
  17618. continue;
  17619. }
  17620. if (light.canAffectMesh(this)) {
  17621. this._lightSources.push(light);
  17622. }
  17623. }
  17624. this._markSubMeshesAsLightDirty();
  17625. };
  17626. AbstractMesh.prototype._resyncLighSource = function (light) {
  17627. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17628. var index = this._lightSources.indexOf(light);
  17629. if (index === -1) {
  17630. if (!isIn) {
  17631. return;
  17632. }
  17633. this._lightSources.push(light);
  17634. }
  17635. else {
  17636. if (isIn) {
  17637. return;
  17638. }
  17639. this._lightSources.splice(index, 1);
  17640. }
  17641. this._markSubMeshesAsLightDirty();
  17642. };
  17643. AbstractMesh.prototype._removeLightSource = function (light) {
  17644. var index = this._lightSources.indexOf(light);
  17645. if (index === -1) {
  17646. return;
  17647. }
  17648. this._lightSources.splice(index, 1);
  17649. this._markSubMeshesAsLightDirty();
  17650. };
  17651. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17652. if (!this.subMeshes) {
  17653. return;
  17654. }
  17655. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17656. var subMesh = _a[_i];
  17657. if (subMesh._materialDefines) {
  17658. func(subMesh._materialDefines);
  17659. }
  17660. }
  17661. };
  17662. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17663. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17664. };
  17665. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17666. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17667. };
  17668. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17669. if (!this.subMeshes) {
  17670. return;
  17671. }
  17672. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17673. var subMesh = _a[_i];
  17674. var material = subMesh.getMaterial();
  17675. if (material) {
  17676. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17677. }
  17678. }
  17679. };
  17680. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17681. /**
  17682. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17683. * Default : (1.0, 1.0, 1.0)
  17684. */
  17685. get: function () {
  17686. return this._scaling;
  17687. },
  17688. /**
  17689. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17690. * Default : (1.0, 1.0, 1.0)
  17691. */
  17692. set: function (newScaling) {
  17693. this._scaling = newScaling;
  17694. if (this.physicsImpostor) {
  17695. this.physicsImpostor.forceUpdate();
  17696. }
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. // Methods
  17702. /**
  17703. * Disables the mesh edger rendering mode.
  17704. * Returns the AbstractMesh.
  17705. */
  17706. AbstractMesh.prototype.disableEdgesRendering = function () {
  17707. if (this._edgesRenderer) {
  17708. this._edgesRenderer.dispose();
  17709. this._edgesRenderer = null;
  17710. }
  17711. return this;
  17712. };
  17713. /**
  17714. * Enables the edge rendering mode on the mesh.
  17715. * This mode makes the mesh edges visible.
  17716. * Returns the AbstractMesh.
  17717. */
  17718. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17719. if (epsilon === void 0) { epsilon = 0.95; }
  17720. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17721. this.disableEdgesRendering();
  17722. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17723. return this;
  17724. };
  17725. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17726. /**
  17727. * Returns true if the mesh is blocked. Used by the class Mesh.
  17728. * Returns the boolean `false` by default.
  17729. */
  17730. get: function () {
  17731. return false;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. /**
  17737. * Returns the mesh itself by default, used by the class Mesh.
  17738. * Returned type : AbstractMesh
  17739. */
  17740. AbstractMesh.prototype.getLOD = function (camera) {
  17741. return this;
  17742. };
  17743. /**
  17744. * Returns 0 by default, used by the class Mesh.
  17745. * Returns an integer.
  17746. */
  17747. AbstractMesh.prototype.getTotalVertices = function () {
  17748. return 0;
  17749. };
  17750. /**
  17751. * Returns null by default, used by the class Mesh.
  17752. * Returned type : integer array
  17753. */
  17754. AbstractMesh.prototype.getIndices = function () {
  17755. return null;
  17756. };
  17757. /**
  17758. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17759. * Returned type : float array or Float32Array
  17760. */
  17761. AbstractMesh.prototype.getVerticesData = function (kind) {
  17762. return null;
  17763. };
  17764. /**
  17765. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17766. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17767. * The `data` are either a numeric array either a Float32Array.
  17768. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17769. * 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).
  17770. * Note that a new underlying VertexBuffer object is created each call.
  17771. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17772. *
  17773. * Possible `kind` values :
  17774. * - BABYLON.VertexBuffer.PositionKind
  17775. * - BABYLON.VertexBuffer.UVKind
  17776. * - BABYLON.VertexBuffer.UV2Kind
  17777. * - BABYLON.VertexBuffer.UV3Kind
  17778. * - BABYLON.VertexBuffer.UV4Kind
  17779. * - BABYLON.VertexBuffer.UV5Kind
  17780. * - BABYLON.VertexBuffer.UV6Kind
  17781. * - BABYLON.VertexBuffer.ColorKind
  17782. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17783. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17784. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17785. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17786. *
  17787. * Returns the Mesh.
  17788. */
  17789. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17790. return this;
  17791. };
  17792. /**
  17793. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17794. * If the mesh has no geometry, it is simply returned as it is.
  17795. * The `data` are either a numeric array either a Float32Array.
  17796. * No new underlying VertexBuffer object is created.
  17797. * 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.
  17798. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17799. *
  17800. * Possible `kind` values :
  17801. * - BABYLON.VertexBuffer.PositionKind
  17802. * - BABYLON.VertexBuffer.UVKind
  17803. * - BABYLON.VertexBuffer.UV2Kind
  17804. * - BABYLON.VertexBuffer.UV3Kind
  17805. * - BABYLON.VertexBuffer.UV4Kind
  17806. * - BABYLON.VertexBuffer.UV5Kind
  17807. * - BABYLON.VertexBuffer.UV6Kind
  17808. * - BABYLON.VertexBuffer.ColorKind
  17809. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17810. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17811. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17812. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17813. *
  17814. * Returns the Mesh.
  17815. */
  17816. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17817. return this;
  17818. };
  17819. /**
  17820. * Sets the mesh indices.
  17821. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17822. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17823. * This method creates a new index buffer each call.
  17824. * Returns the Mesh.
  17825. */
  17826. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17827. return this;
  17828. };
  17829. /** Returns false by default, used by the class Mesh.
  17830. * Returns a boolean
  17831. */
  17832. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17833. return false;
  17834. };
  17835. /**
  17836. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17837. * Returns a BoundingInfo
  17838. */
  17839. AbstractMesh.prototype.getBoundingInfo = function () {
  17840. if (this._masterMesh) {
  17841. return this._masterMesh.getBoundingInfo();
  17842. }
  17843. if (!this._boundingInfo) {
  17844. // this._boundingInfo is being created here
  17845. this._updateBoundingInfo();
  17846. }
  17847. // cannot be null.
  17848. return this._boundingInfo;
  17849. };
  17850. /**
  17851. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17852. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17853. */
  17854. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17855. if (includeDescendants === void 0) { includeDescendants = true; }
  17856. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17857. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17858. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17859. if (maxDimension === 0) {
  17860. return this;
  17861. }
  17862. var scale = 1 / maxDimension;
  17863. this.scaling.scaleInPlace(scale);
  17864. return this;
  17865. };
  17866. /**
  17867. * Sets a mesh new object BoundingInfo.
  17868. * Returns the AbstractMesh.
  17869. */
  17870. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17871. this._boundingInfo = boundingInfo;
  17872. return this;
  17873. };
  17874. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17875. get: function () {
  17876. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. AbstractMesh.prototype._preActivate = function () {
  17882. };
  17883. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17884. };
  17885. AbstractMesh.prototype._activate = function (renderId) {
  17886. this._renderId = renderId;
  17887. };
  17888. /**
  17889. * Returns the latest update of the World matrix
  17890. * Returns a Matrix.
  17891. */
  17892. AbstractMesh.prototype.getWorldMatrix = function () {
  17893. if (this._masterMesh) {
  17894. return this._masterMesh.getWorldMatrix();
  17895. }
  17896. return _super.prototype.getWorldMatrix.call(this);
  17897. };
  17898. /**
  17899. * Returns the latest update of the World matrix determinant.
  17900. */
  17901. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17902. if (this._masterMesh) {
  17903. return this._masterMesh._getWorldMatrixDeterminant();
  17904. }
  17905. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17906. };
  17907. // ================================== Point of View Movement =================================
  17908. /**
  17909. * Perform relative position change from the point of view of behind the front of the mesh.
  17910. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17911. * Supports definition of mesh facing forward or backward.
  17912. * @param {number} amountRight
  17913. * @param {number} amountUp
  17914. * @param {number} amountForward
  17915. *
  17916. * Returns the AbstractMesh.
  17917. */
  17918. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17919. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17920. return this;
  17921. };
  17922. /**
  17923. * Calculate relative position change from the point of view of behind the front of the mesh.
  17924. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17925. * Supports definition of mesh facing forward or backward.
  17926. * @param {number} amountRight
  17927. * @param {number} amountUp
  17928. * @param {number} amountForward
  17929. *
  17930. * Returns a new Vector3.
  17931. */
  17932. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17933. var rotMatrix = new BABYLON.Matrix();
  17934. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17935. rotQuaternion.toRotationMatrix(rotMatrix);
  17936. var translationDelta = BABYLON.Vector3.Zero();
  17937. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17938. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17939. return translationDelta;
  17940. };
  17941. // ================================== Point of View Rotation =================================
  17942. /**
  17943. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17944. * Supports definition of mesh facing forward or backward.
  17945. * @param {number} flipBack
  17946. * @param {number} twirlClockwise
  17947. * @param {number} tiltRight
  17948. *
  17949. * Returns the AbstractMesh.
  17950. */
  17951. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17952. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17953. return this;
  17954. };
  17955. /**
  17956. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17957. * Supports definition of mesh facing forward or backward.
  17958. * @param {number} flipBack
  17959. * @param {number} twirlClockwise
  17960. * @param {number} tiltRight
  17961. *
  17962. * Returns a new Vector3.
  17963. */
  17964. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17965. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17966. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17967. };
  17968. /**
  17969. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17970. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17971. */
  17972. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17973. if (includeDescendants === void 0) { includeDescendants = true; }
  17974. this.computeWorldMatrix(true);
  17975. var min;
  17976. var max;
  17977. var boundingInfo = this.getBoundingInfo();
  17978. if (!this.subMeshes) {
  17979. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17980. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17981. }
  17982. else {
  17983. min = boundingInfo.boundingBox.minimumWorld;
  17984. max = boundingInfo.boundingBox.maximumWorld;
  17985. }
  17986. if (includeDescendants) {
  17987. var descendants = this.getDescendants(false);
  17988. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17989. var descendant = descendants_1[_i];
  17990. var childMesh = descendant;
  17991. childMesh.computeWorldMatrix(true);
  17992. //make sure we have the needed params to get mix and max
  17993. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17994. continue;
  17995. }
  17996. var childBoundingInfo = childMesh.getBoundingInfo();
  17997. var boundingBox = childBoundingInfo.boundingBox;
  17998. var minBox = boundingBox.minimumWorld;
  17999. var maxBox = boundingBox.maximumWorld;
  18000. BABYLON.Tools.CheckExtends(minBox, min, max);
  18001. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18002. }
  18003. }
  18004. return {
  18005. min: min,
  18006. max: max
  18007. };
  18008. };
  18009. /**
  18010. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18011. * Returns the AbstractMesh.
  18012. */
  18013. AbstractMesh.prototype._updateBoundingInfo = function () {
  18014. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18015. this._boundingInfo.update(this.worldMatrixFromCache);
  18016. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18017. return this;
  18018. };
  18019. /**
  18020. * Update a mesh's children BoundingInfo objects only.
  18021. * Returns the AbstractMesh.
  18022. */
  18023. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18024. if (!this.subMeshes) {
  18025. return this;
  18026. }
  18027. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18028. var subMesh = this.subMeshes[subIndex];
  18029. if (!subMesh.IsGlobal) {
  18030. subMesh.updateBoundingInfo(matrix);
  18031. }
  18032. }
  18033. return this;
  18034. };
  18035. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18036. // Bounding info
  18037. this._updateBoundingInfo();
  18038. };
  18039. /**
  18040. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18041. * A mesh is in the frustum if its bounding box intersects the frustum.
  18042. * Boolean returned.
  18043. */
  18044. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18045. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18046. };
  18047. /**
  18048. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18049. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18050. * Boolean returned.
  18051. */
  18052. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18053. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18054. ;
  18055. };
  18056. /**
  18057. * True if the mesh intersects another mesh or a SolidParticle object.
  18058. * 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)
  18059. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18060. * Returns a boolean.
  18061. */
  18062. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18063. if (precise === void 0) { precise = false; }
  18064. if (!this._boundingInfo || !mesh._boundingInfo) {
  18065. return false;
  18066. }
  18067. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18068. return true;
  18069. }
  18070. if (includeDescendants) {
  18071. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18072. var child = _a[_i];
  18073. if (child.intersectsMesh(mesh, precise, true)) {
  18074. return true;
  18075. }
  18076. }
  18077. }
  18078. return false;
  18079. };
  18080. /**
  18081. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18082. * Returns a boolean.
  18083. */
  18084. AbstractMesh.prototype.intersectsPoint = function (point) {
  18085. if (!this._boundingInfo) {
  18086. return false;
  18087. }
  18088. return this._boundingInfo.intersectsPoint(point);
  18089. };
  18090. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18091. return this.physicsImpostor;
  18092. };
  18093. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18094. if (camera === void 0) { camera = null; }
  18095. if (!camera) {
  18096. camera = this.getScene().activeCamera;
  18097. }
  18098. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18099. };
  18100. /**
  18101. * Returns the distance from the mesh to the active camera.
  18102. * Returns a float.
  18103. */
  18104. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18105. if (camera === void 0) { camera = null; }
  18106. if (!camera) {
  18107. camera = this.getScene().activeCamera;
  18108. }
  18109. return this.absolutePosition.subtract(camera.position).length();
  18110. };
  18111. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18112. if (!this.physicsImpostor) {
  18113. return this;
  18114. }
  18115. this.physicsImpostor.applyImpulse(force, contactPoint);
  18116. return this;
  18117. };
  18118. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18119. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18120. return this;
  18121. }
  18122. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18123. mainPivot: pivot1,
  18124. connectedPivot: pivot2,
  18125. nativeParams: options
  18126. });
  18127. return this;
  18128. };
  18129. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18130. // Collisions
  18131. /**
  18132. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18133. * Default `false`.
  18134. */
  18135. get: function () {
  18136. return this._checkCollisions;
  18137. },
  18138. set: function (collisionEnabled) {
  18139. this._checkCollisions = collisionEnabled;
  18140. if (this.getScene().workerCollisions) {
  18141. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18142. }
  18143. },
  18144. enumerable: true,
  18145. configurable: true
  18146. });
  18147. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18148. /**
  18149. * Gets Collider object used to compute collisions (not physics)
  18150. */
  18151. get: function () {
  18152. return this._collider;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18158. var globalPosition = this.getAbsolutePosition();
  18159. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18160. if (!this._collider) {
  18161. this._collider = new BABYLON.Collider();
  18162. }
  18163. this._collider._radius = this.ellipsoid;
  18164. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18165. return this;
  18166. };
  18167. // Submeshes octree
  18168. /**
  18169. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18170. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18171. * Returns an Octree of submeshes.
  18172. */
  18173. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18174. if (maxCapacity === void 0) { maxCapacity = 64; }
  18175. if (maxDepth === void 0) { maxDepth = 2; }
  18176. if (!this._submeshesOctree) {
  18177. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18178. }
  18179. this.computeWorldMatrix(true);
  18180. var boundingInfo = this.getBoundingInfo();
  18181. // Update octree
  18182. var bbox = boundingInfo.boundingBox;
  18183. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18184. return this._submeshesOctree;
  18185. };
  18186. // Collisions
  18187. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18188. this._generatePointsArray();
  18189. if (!this._positions) {
  18190. return this;
  18191. }
  18192. // Transformation
  18193. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18194. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18195. subMesh._lastColliderWorldVertices = [];
  18196. subMesh._trianglePlanes = [];
  18197. var start = subMesh.verticesStart;
  18198. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18199. for (var i = start; i < end; i++) {
  18200. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18201. }
  18202. }
  18203. // Collide
  18204. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18205. if (collider.collisionFound) {
  18206. collider.collidedMesh = this;
  18207. }
  18208. return this;
  18209. };
  18210. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18211. var subMeshes;
  18212. var len;
  18213. // Octrees
  18214. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18215. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18216. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18217. len = intersections.length;
  18218. subMeshes = intersections.data;
  18219. }
  18220. else {
  18221. subMeshes = this.subMeshes;
  18222. len = subMeshes.length;
  18223. }
  18224. for (var index = 0; index < len; index++) {
  18225. var subMesh = subMeshes[index];
  18226. // Bounding test
  18227. if (len > 1 && !subMesh._checkCollision(collider))
  18228. continue;
  18229. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18230. }
  18231. return this;
  18232. };
  18233. AbstractMesh.prototype._checkCollision = function (collider) {
  18234. // Bounding box test
  18235. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18236. return this;
  18237. // Transformation matrix
  18238. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18239. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18240. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18241. return this;
  18242. };
  18243. // Picking
  18244. AbstractMesh.prototype._generatePointsArray = function () {
  18245. return false;
  18246. };
  18247. /**
  18248. * Checks if the passed Ray intersects with the mesh.
  18249. * Returns an object PickingInfo.
  18250. */
  18251. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18252. var pickingInfo = new BABYLON.PickingInfo();
  18253. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18254. return pickingInfo;
  18255. }
  18256. if (!this._generatePointsArray()) {
  18257. return pickingInfo;
  18258. }
  18259. var intersectInfo = null;
  18260. // Octrees
  18261. var subMeshes;
  18262. var len;
  18263. if (this._submeshesOctree && this.useOctreeForPicking) {
  18264. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18265. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18266. len = intersections.length;
  18267. subMeshes = intersections.data;
  18268. }
  18269. else {
  18270. subMeshes = this.subMeshes;
  18271. len = subMeshes.length;
  18272. }
  18273. for (var index = 0; index < len; index++) {
  18274. var subMesh = subMeshes[index];
  18275. // Bounding test
  18276. if (len > 1 && !subMesh.canIntersects(ray))
  18277. continue;
  18278. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18279. if (currentIntersectInfo) {
  18280. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18281. intersectInfo = currentIntersectInfo;
  18282. intersectInfo.subMeshId = index;
  18283. if (fastCheck) {
  18284. break;
  18285. }
  18286. }
  18287. }
  18288. }
  18289. if (intersectInfo) {
  18290. // Get picked point
  18291. var world = this.getWorldMatrix();
  18292. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18293. var direction = ray.direction.clone();
  18294. direction = direction.scale(intersectInfo.distance);
  18295. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18296. var pickedPoint = worldOrigin.add(worldDirection);
  18297. // Return result
  18298. pickingInfo.hit = true;
  18299. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18300. pickingInfo.pickedPoint = pickedPoint;
  18301. pickingInfo.pickedMesh = this;
  18302. pickingInfo.bu = intersectInfo.bu || 0;
  18303. pickingInfo.bv = intersectInfo.bv || 0;
  18304. pickingInfo.faceId = intersectInfo.faceId;
  18305. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18306. return pickingInfo;
  18307. }
  18308. return pickingInfo;
  18309. };
  18310. /**
  18311. * Clones the mesh, used by the class Mesh.
  18312. * Just returns `null` for an AbstractMesh.
  18313. */
  18314. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18315. return null;
  18316. };
  18317. /**
  18318. * Disposes all the mesh submeshes.
  18319. * Returns the AbstractMesh.
  18320. */
  18321. AbstractMesh.prototype.releaseSubMeshes = function () {
  18322. if (this.subMeshes) {
  18323. while (this.subMeshes.length) {
  18324. this.subMeshes[0].dispose();
  18325. }
  18326. }
  18327. else {
  18328. this.subMeshes = new Array();
  18329. }
  18330. return this;
  18331. };
  18332. /**
  18333. * Disposes the AbstractMesh.
  18334. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18335. * Returns nothing.
  18336. */
  18337. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18338. var _this = this;
  18339. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18340. var index;
  18341. // Action manager
  18342. if (this.actionManager !== undefined && this.actionManager !== null) {
  18343. this.actionManager.dispose();
  18344. this.actionManager = null;
  18345. }
  18346. // Skeleton
  18347. this.skeleton = null;
  18348. // Physics
  18349. if (this.physicsImpostor) {
  18350. this.physicsImpostor.dispose();
  18351. }
  18352. // Intersections in progress
  18353. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18354. var other = this._intersectionsInProgress[index];
  18355. var pos = other._intersectionsInProgress.indexOf(this);
  18356. other._intersectionsInProgress.splice(pos, 1);
  18357. }
  18358. this._intersectionsInProgress = [];
  18359. // Lights
  18360. var lights = this.getScene().lights;
  18361. lights.forEach(function (light) {
  18362. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18363. if (meshIndex !== -1) {
  18364. light.includedOnlyMeshes.splice(meshIndex, 1);
  18365. }
  18366. meshIndex = light.excludedMeshes.indexOf(_this);
  18367. if (meshIndex !== -1) {
  18368. light.excludedMeshes.splice(meshIndex, 1);
  18369. }
  18370. // Shadow generators
  18371. var generator = light.getShadowGenerator();
  18372. if (generator) {
  18373. var shadowMap = generator.getShadowMap();
  18374. if (shadowMap && shadowMap.renderList) {
  18375. meshIndex = shadowMap.renderList.indexOf(_this);
  18376. if (meshIndex !== -1) {
  18377. shadowMap.renderList.splice(meshIndex, 1);
  18378. }
  18379. }
  18380. }
  18381. });
  18382. // Edges
  18383. if (this._edgesRenderer) {
  18384. this._edgesRenderer.dispose();
  18385. this._edgesRenderer = null;
  18386. }
  18387. // SubMeshes
  18388. if (this.getClassName() !== "InstancedMesh") {
  18389. this.releaseSubMeshes();
  18390. }
  18391. // Octree
  18392. var sceneOctree = this.getScene().selectionOctree;
  18393. if (sceneOctree !== undefined && sceneOctree !== null) {
  18394. var index = sceneOctree.dynamicContent.indexOf(this);
  18395. if (index !== -1) {
  18396. sceneOctree.dynamicContent.splice(index, 1);
  18397. }
  18398. }
  18399. // Query
  18400. var engine = this.getScene().getEngine();
  18401. if (this._occlusionQuery) {
  18402. this._isOcclusionQueryInProgress = false;
  18403. engine.deleteQuery(this._occlusionQuery);
  18404. this._occlusionQuery = null;
  18405. }
  18406. // Engine
  18407. engine.wipeCaches();
  18408. // Remove from scene
  18409. this.getScene().removeMesh(this);
  18410. if (disposeMaterialAndTextures) {
  18411. if (this.material) {
  18412. this.material.dispose(false, true);
  18413. }
  18414. }
  18415. if (!doNotRecurse) {
  18416. // Particles
  18417. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18418. if (this.getScene().particleSystems[index].emitter === this) {
  18419. this.getScene().particleSystems[index].dispose();
  18420. index--;
  18421. }
  18422. }
  18423. }
  18424. // facet data
  18425. if (this._facetDataEnabled) {
  18426. this.disableFacetData();
  18427. }
  18428. this.onAfterWorldMatrixUpdateObservable.clear();
  18429. this.onCollideObservable.clear();
  18430. this.onCollisionPositionChangeObservable.clear();
  18431. _super.prototype.dispose.call(this, doNotRecurse);
  18432. };
  18433. /**
  18434. * Adds the passed mesh as a child to the current mesh.
  18435. * Returns the AbstractMesh.
  18436. */
  18437. AbstractMesh.prototype.addChild = function (mesh) {
  18438. mesh.setParent(this);
  18439. return this;
  18440. };
  18441. /**
  18442. * Removes the passed mesh from the current mesh children list.
  18443. * Returns the AbstractMesh.
  18444. */
  18445. AbstractMesh.prototype.removeChild = function (mesh) {
  18446. mesh.setParent(null);
  18447. return this;
  18448. };
  18449. // Facet data
  18450. /**
  18451. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18452. * Returns the AbstractMesh.
  18453. */
  18454. AbstractMesh.prototype._initFacetData = function () {
  18455. if (!this._facetNormals) {
  18456. this._facetNormals = new Array();
  18457. }
  18458. if (!this._facetPositions) {
  18459. this._facetPositions = new Array();
  18460. }
  18461. if (!this._facetPartitioning) {
  18462. this._facetPartitioning = new Array();
  18463. }
  18464. this._facetNb = (this.getIndices().length / 3) | 0;
  18465. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18466. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18467. for (var f = 0; f < this._facetNb; f++) {
  18468. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18469. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18470. }
  18471. this._facetDataEnabled = true;
  18472. return this;
  18473. };
  18474. /**
  18475. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18476. * This method can be called within the render loop.
  18477. * 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.
  18478. * Returns the AbstractMesh.
  18479. */
  18480. AbstractMesh.prototype.updateFacetData = function () {
  18481. if (!this._facetDataEnabled) {
  18482. this._initFacetData();
  18483. }
  18484. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18485. var indices = this.getIndices();
  18486. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18487. var bInfo = this.getBoundingInfo();
  18488. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18489. // init arrays, matrix and sort function on first call
  18490. this._facetDepthSortEnabled = true;
  18491. if (indices instanceof Uint16Array) {
  18492. this._depthSortedIndices = new Uint16Array(indices);
  18493. }
  18494. else if (indices instanceof Uint32Array) {
  18495. this._depthSortedIndices = new Uint32Array(indices);
  18496. }
  18497. else {
  18498. var needs32bits = false;
  18499. for (var i = 0; i < indices.length; i++) {
  18500. if (indices[i] > 65535) {
  18501. needs32bits = true;
  18502. break;
  18503. }
  18504. }
  18505. if (needs32bits) {
  18506. this._depthSortedIndices = new Uint32Array(indices);
  18507. }
  18508. else {
  18509. this._depthSortedIndices = new Uint16Array(indices);
  18510. }
  18511. }
  18512. this._facetDepthSortFunction = function (f1, f2) {
  18513. return (f2.sqDistance - f1.sqDistance);
  18514. };
  18515. if (!this._facetDepthSortFrom) {
  18516. var camera = this.getScene().activeCamera;
  18517. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18518. }
  18519. this._depthSortedFacets = [];
  18520. for (var f = 0; f < this._facetNb; f++) {
  18521. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18522. this._depthSortedFacets.push(depthSortedFacet);
  18523. }
  18524. this._invertedMatrix = BABYLON.Matrix.Identity();
  18525. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18526. }
  18527. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18528. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18529. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18530. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18531. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18532. this._subDiv.max = this._partitioningSubdivisions;
  18533. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18534. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18535. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18536. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18537. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18538. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18539. // set the parameters for ComputeNormals()
  18540. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18541. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18542. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18543. this._facetParameters.bInfo = bInfo;
  18544. this._facetParameters.bbSize = this._bbSize;
  18545. this._facetParameters.subDiv = this._subDiv;
  18546. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18547. this._facetParameters.depthSort = this._facetDepthSort;
  18548. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18549. this.computeWorldMatrix(true);
  18550. this._worldMatrix.invertToRef(this._invertedMatrix);
  18551. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18552. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18553. }
  18554. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18555. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18556. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18557. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18558. var l = (this._depthSortedIndices.length / 3) | 0;
  18559. for (var f = 0; f < l; f++) {
  18560. var sind = this._depthSortedFacets[f].ind;
  18561. this._depthSortedIndices[f * 3] = indices[sind];
  18562. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18563. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18564. }
  18565. this.updateIndices(this._depthSortedIndices);
  18566. }
  18567. return this;
  18568. };
  18569. /**
  18570. * Returns the facetLocalNormals array.
  18571. * The normals are expressed in the mesh local space.
  18572. */
  18573. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18574. if (!this._facetNormals) {
  18575. this.updateFacetData();
  18576. }
  18577. return this._facetNormals;
  18578. };
  18579. /**
  18580. * Returns the facetLocalPositions array.
  18581. * The facet positions are expressed in the mesh local space.
  18582. */
  18583. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18584. if (!this._facetPositions) {
  18585. this.updateFacetData();
  18586. }
  18587. return this._facetPositions;
  18588. };
  18589. /**
  18590. * Returns the facetLocalPartioning array.
  18591. */
  18592. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18593. if (!this._facetPartitioning) {
  18594. this.updateFacetData();
  18595. }
  18596. return this._facetPartitioning;
  18597. };
  18598. /**
  18599. * Returns the i-th facet position in the world system.
  18600. * This method allocates a new Vector3 per call.
  18601. */
  18602. AbstractMesh.prototype.getFacetPosition = function (i) {
  18603. var pos = BABYLON.Vector3.Zero();
  18604. this.getFacetPositionToRef(i, pos);
  18605. return pos;
  18606. };
  18607. /**
  18608. * Sets the reference Vector3 with the i-th facet position in the world system.
  18609. * Returns the AbstractMesh.
  18610. */
  18611. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18612. var localPos = (this.getFacetLocalPositions())[i];
  18613. var world = this.getWorldMatrix();
  18614. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18615. return this;
  18616. };
  18617. /**
  18618. * Returns the i-th facet normal in the world system.
  18619. * This method allocates a new Vector3 per call.
  18620. */
  18621. AbstractMesh.prototype.getFacetNormal = function (i) {
  18622. var norm = BABYLON.Vector3.Zero();
  18623. this.getFacetNormalToRef(i, norm);
  18624. return norm;
  18625. };
  18626. /**
  18627. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18628. * Returns the AbstractMesh.
  18629. */
  18630. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18631. var localNorm = (this.getFacetLocalNormals())[i];
  18632. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18633. return this;
  18634. };
  18635. /**
  18636. * 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).
  18637. */
  18638. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18639. var bInfo = this.getBoundingInfo();
  18640. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18641. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18642. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18643. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18644. return null;
  18645. }
  18646. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18647. };
  18648. /**
  18649. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18650. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18651. * 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.
  18652. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18653. * 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.
  18654. */
  18655. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18656. if (checkFace === void 0) { checkFace = false; }
  18657. if (facing === void 0) { facing = true; }
  18658. var world = this.getWorldMatrix();
  18659. var invMat = BABYLON.Tmp.Matrix[5];
  18660. world.invertToRef(invMat);
  18661. var invVect = BABYLON.Tmp.Vector3[8];
  18662. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18663. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18664. if (projected) {
  18665. // tranform the local computed projected vector to world coordinates
  18666. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18667. }
  18668. return closest;
  18669. };
  18670. /**
  18671. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18672. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18673. * 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.
  18674. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18675. * 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.
  18676. */
  18677. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18678. if (checkFace === void 0) { checkFace = false; }
  18679. if (facing === void 0) { facing = true; }
  18680. var closest = null;
  18681. var tmpx = 0.0;
  18682. var tmpy = 0.0;
  18683. var tmpz = 0.0;
  18684. var d = 0.0; // tmp dot facet normal * facet position
  18685. var t0 = 0.0;
  18686. var projx = 0.0;
  18687. var projy = 0.0;
  18688. var projz = 0.0;
  18689. // Get all the facets in the same partitioning block than (x, y, z)
  18690. var facetPositions = this.getFacetLocalPositions();
  18691. var facetNormals = this.getFacetLocalNormals();
  18692. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18693. if (!facetsInBlock) {
  18694. return null;
  18695. }
  18696. // Get the closest facet to (x, y, z)
  18697. var shortest = Number.MAX_VALUE; // init distance vars
  18698. var tmpDistance = shortest;
  18699. var fib; // current facet in the block
  18700. var norm; // current facet normal
  18701. var p0; // current facet barycenter position
  18702. // loop on all the facets in the current partitioning block
  18703. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18704. fib = facetsInBlock[idx];
  18705. norm = facetNormals[fib];
  18706. p0 = facetPositions[fib];
  18707. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18708. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18709. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18710. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18711. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18712. projx = x + norm.x * t0;
  18713. projy = y + norm.y * t0;
  18714. projz = z + norm.z * t0;
  18715. tmpx = projx - x;
  18716. tmpy = projy - y;
  18717. tmpz = projz - z;
  18718. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18719. if (tmpDistance < shortest) {
  18720. shortest = tmpDistance;
  18721. closest = fib;
  18722. if (projected) {
  18723. projected.x = projx;
  18724. projected.y = projy;
  18725. projected.z = projz;
  18726. }
  18727. }
  18728. }
  18729. }
  18730. return closest;
  18731. };
  18732. /**
  18733. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18734. */
  18735. AbstractMesh.prototype.getFacetDataParameters = function () {
  18736. return this._facetParameters;
  18737. };
  18738. /**
  18739. * Disables the feature FacetData and frees the related memory.
  18740. * Returns the AbstractMesh.
  18741. */
  18742. AbstractMesh.prototype.disableFacetData = function () {
  18743. if (this._facetDataEnabled) {
  18744. this._facetDataEnabled = false;
  18745. this._facetPositions = new Array();
  18746. this._facetNormals = new Array();
  18747. this._facetPartitioning = new Array();
  18748. this._facetParameters = null;
  18749. this._depthSortedIndices = new Uint32Array(0);
  18750. }
  18751. return this;
  18752. };
  18753. /**
  18754. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18755. * Returns the mesh.
  18756. */
  18757. AbstractMesh.prototype.updateIndices = function (indices) {
  18758. return this;
  18759. };
  18760. /**
  18761. * The mesh Geometry. Actually used by the Mesh object.
  18762. * Returns a blank geometry object.
  18763. */
  18764. /**
  18765. * Creates new normals data for the mesh.
  18766. * @param updatable.
  18767. */
  18768. AbstractMesh.prototype.createNormals = function (updatable) {
  18769. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18770. var indices = this.getIndices();
  18771. var normals;
  18772. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18773. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18774. }
  18775. else {
  18776. normals = [];
  18777. }
  18778. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18779. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18780. };
  18781. /**
  18782. * Align the mesh with a normal.
  18783. * Returns the mesh.
  18784. */
  18785. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18786. if (!upDirection) {
  18787. upDirection = BABYLON.Axis.Y;
  18788. }
  18789. var axisX = BABYLON.Tmp.Vector3[0];
  18790. var axisZ = BABYLON.Tmp.Vector3[1];
  18791. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18792. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18793. if (this.rotationQuaternion) {
  18794. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18795. }
  18796. else {
  18797. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18798. }
  18799. return this;
  18800. };
  18801. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18802. var engine = this.getEngine();
  18803. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18804. this._isOccluded = false;
  18805. return;
  18806. }
  18807. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18808. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18809. if (isOcclusionQueryAvailable) {
  18810. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18811. this._isOcclusionQueryInProgress = false;
  18812. this._occlusionInternalRetryCounter = 0;
  18813. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18814. }
  18815. else {
  18816. this._occlusionInternalRetryCounter++;
  18817. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18818. this._isOcclusionQueryInProgress = false;
  18819. this._occlusionInternalRetryCounter = 0;
  18820. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18821. // if strict continue the last state of the object.
  18822. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18823. }
  18824. else {
  18825. return;
  18826. }
  18827. }
  18828. }
  18829. var scene = this.getScene();
  18830. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18831. if (!this._occlusionQuery) {
  18832. this._occlusionQuery = engine.createQuery();
  18833. }
  18834. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18835. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18836. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18837. this._isOcclusionQueryInProgress = true;
  18838. };
  18839. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18840. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18841. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18842. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18843. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18844. return AbstractMesh;
  18845. }(BABYLON.TransformNode));
  18846. BABYLON.AbstractMesh = AbstractMesh;
  18847. })(BABYLON || (BABYLON = {}));
  18848. //# sourceMappingURL=babylon.abstractMesh.js.map
  18849. var BABYLON;
  18850. (function (BABYLON) {
  18851. /**
  18852. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18853. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18854. * 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.
  18855. */
  18856. var Light = /** @class */ (function (_super) {
  18857. __extends(Light, _super);
  18858. /**
  18859. * Creates a Light object in the scene.
  18860. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18861. * @param name The firendly name of the light
  18862. * @param scene The scene the light belongs too
  18863. */
  18864. function Light(name, scene) {
  18865. var _this = _super.call(this, name, scene) || this;
  18866. /**
  18867. * Diffuse gives the basic color to an object.
  18868. */
  18869. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18870. /**
  18871. * Specular produces a highlight color on an object.
  18872. * Note: This is note affecting PBR materials.
  18873. */
  18874. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18875. /**
  18876. * Strength of the light.
  18877. * Note: By default it is define in the framework own unit.
  18878. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18879. */
  18880. _this.intensity = 1.0;
  18881. /**
  18882. * Defines how far from the source the light is impacting in scene units.
  18883. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18884. */
  18885. _this.range = Number.MAX_VALUE;
  18886. /**
  18887. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18888. * of light.
  18889. */
  18890. _this._photometricScale = 1.0;
  18891. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18892. _this._radius = 0.00001;
  18893. /**
  18894. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18895. * exceeding the number allowed of the materials.
  18896. */
  18897. _this.renderPriority = 0;
  18898. /**
  18899. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18900. * the current shadow generator.
  18901. */
  18902. _this.shadowEnabled = true;
  18903. _this._excludeWithLayerMask = 0;
  18904. _this._includeOnlyWithLayerMask = 0;
  18905. _this._lightmapMode = 0;
  18906. /**
  18907. * @ignore Internal use only.
  18908. */
  18909. _this._excludedMeshesIds = new Array();
  18910. /**
  18911. * @ignore Internal use only.
  18912. */
  18913. _this._includedOnlyMeshesIds = new Array();
  18914. _this.getScene().addLight(_this);
  18915. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18916. _this._buildUniformLayout();
  18917. _this.includedOnlyMeshes = new Array();
  18918. _this.excludedMeshes = new Array();
  18919. _this._resyncMeshes();
  18920. return _this;
  18921. }
  18922. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18923. /**
  18924. * If every light affecting the material is in this lightmapMode,
  18925. * material.lightmapTexture adds or multiplies
  18926. * (depends on material.useLightmapAsShadowmap)
  18927. * after every other light calculations.
  18928. */
  18929. get: function () {
  18930. return Light._LIGHTMAP_DEFAULT;
  18931. },
  18932. enumerable: true,
  18933. configurable: true
  18934. });
  18935. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18936. /**
  18937. * material.lightmapTexture as only diffuse lighting from this light
  18938. * adds only specular lighting from this light
  18939. * adds dynamic shadows
  18940. */
  18941. get: function () {
  18942. return Light._LIGHTMAP_SPECULAR;
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18948. /**
  18949. * material.lightmapTexture as only lighting
  18950. * no light calculation from this light
  18951. * only adds dynamic shadows from this light
  18952. */
  18953. get: function () {
  18954. return Light._LIGHTMAP_SHADOWSONLY;
  18955. },
  18956. enumerable: true,
  18957. configurable: true
  18958. });
  18959. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18960. /**
  18961. * Each light type uses the default quantity according to its type:
  18962. * point/spot lights use luminous intensity
  18963. * directional lights use illuminance
  18964. */
  18965. get: function () {
  18966. return Light._INTENSITYMODE_AUTOMATIC;
  18967. },
  18968. enumerable: true,
  18969. configurable: true
  18970. });
  18971. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18972. /**
  18973. * lumen (lm)
  18974. */
  18975. get: function () {
  18976. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18982. /**
  18983. * candela (lm/sr)
  18984. */
  18985. get: function () {
  18986. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18992. /**
  18993. * lux (lm/m^2)
  18994. */
  18995. get: function () {
  18996. return Light._INTENSITYMODE_ILLUMINANCE;
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19002. /**
  19003. * nit (cd/m^2)
  19004. */
  19005. get: function () {
  19006. return Light._INTENSITYMODE_LUMINANCE;
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19012. /**
  19013. * Light type const id of the point light.
  19014. */
  19015. get: function () {
  19016. return Light._LIGHTTYPEID_POINTLIGHT;
  19017. },
  19018. enumerable: true,
  19019. configurable: true
  19020. });
  19021. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19022. /**
  19023. * Light type const id of the directional light.
  19024. */
  19025. get: function () {
  19026. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19032. /**
  19033. * Light type const id of the spot light.
  19034. */
  19035. get: function () {
  19036. return Light._LIGHTTYPEID_SPOTLIGHT;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19042. /**
  19043. * Light type const id of the hemispheric light.
  19044. */
  19045. get: function () {
  19046. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(Light.prototype, "intensityMode", {
  19052. /**
  19053. * Gets the photometric scale used to interpret the intensity.
  19054. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19055. */
  19056. get: function () {
  19057. return this._intensityMode;
  19058. },
  19059. /**
  19060. * Sets the photometric scale used to interpret the intensity.
  19061. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19062. */
  19063. set: function (value) {
  19064. this._intensityMode = value;
  19065. this._computePhotometricScale();
  19066. },
  19067. enumerable: true,
  19068. configurable: true
  19069. });
  19070. ;
  19071. ;
  19072. Object.defineProperty(Light.prototype, "radius", {
  19073. /**
  19074. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19075. */
  19076. get: function () {
  19077. return this._radius;
  19078. },
  19079. /**
  19080. * sets the light radius used by PBR Materials to simulate soft area lights.
  19081. */
  19082. set: function (value) {
  19083. this._radius = value;
  19084. this._computePhotometricScale();
  19085. },
  19086. enumerable: true,
  19087. configurable: true
  19088. });
  19089. ;
  19090. ;
  19091. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19092. /**
  19093. * Gets the only meshes impacted by this light.
  19094. */
  19095. get: function () {
  19096. return this._includedOnlyMeshes;
  19097. },
  19098. /**
  19099. * Sets the only meshes impacted by this light.
  19100. */
  19101. set: function (value) {
  19102. this._includedOnlyMeshes = value;
  19103. this._hookArrayForIncludedOnly(value);
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19109. /**
  19110. * Gets the meshes not impacted by this light.
  19111. */
  19112. get: function () {
  19113. return this._excludedMeshes;
  19114. },
  19115. /**
  19116. * Sets the meshes not impacted by this light.
  19117. */
  19118. set: function (value) {
  19119. this._excludedMeshes = value;
  19120. this._hookArrayForExcluded(value);
  19121. },
  19122. enumerable: true,
  19123. configurable: true
  19124. });
  19125. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19126. /**
  19127. * Gets the layer id use to find what meshes are not impacted by the light.
  19128. * Inactive if 0
  19129. */
  19130. get: function () {
  19131. return this._excludeWithLayerMask;
  19132. },
  19133. /**
  19134. * Sets the layer id use to find what meshes are not impacted by the light.
  19135. * Inactive if 0
  19136. */
  19137. set: function (value) {
  19138. this._excludeWithLayerMask = value;
  19139. this._resyncMeshes();
  19140. },
  19141. enumerable: true,
  19142. configurable: true
  19143. });
  19144. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19145. /**
  19146. * Gets the layer id use to find what meshes are impacted by the light.
  19147. * Inactive if 0
  19148. */
  19149. get: function () {
  19150. return this._includeOnlyWithLayerMask;
  19151. },
  19152. /**
  19153. * Sets the layer id use to find what meshes are impacted by the light.
  19154. * Inactive if 0
  19155. */
  19156. set: function (value) {
  19157. this._includeOnlyWithLayerMask = value;
  19158. this._resyncMeshes();
  19159. },
  19160. enumerable: true,
  19161. configurable: true
  19162. });
  19163. Object.defineProperty(Light.prototype, "lightmapMode", {
  19164. /**
  19165. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19166. */
  19167. get: function () {
  19168. return this._lightmapMode;
  19169. },
  19170. /**
  19171. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19172. */
  19173. set: function (value) {
  19174. if (this._lightmapMode === value) {
  19175. return;
  19176. }
  19177. this._lightmapMode = value;
  19178. this._markMeshesAsLightDirty();
  19179. },
  19180. enumerable: true,
  19181. configurable: true
  19182. });
  19183. /**
  19184. * Returns the string "Light".
  19185. * @returns the class name
  19186. */
  19187. Light.prototype.getClassName = function () {
  19188. return "Light";
  19189. };
  19190. /**
  19191. * Converts the light information to a readable string for debug purpose.
  19192. * @param fullDetails Supports for multiple levels of logging within scene loading
  19193. * @returns the human readable light info
  19194. */
  19195. Light.prototype.toString = function (fullDetails) {
  19196. var ret = "Name: " + this.name;
  19197. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19198. if (this.animations) {
  19199. for (var i = 0; i < this.animations.length; i++) {
  19200. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19201. }
  19202. }
  19203. if (fullDetails) {
  19204. }
  19205. return ret;
  19206. };
  19207. /**
  19208. * Set the enabled state of this node.
  19209. * @param value - the new enabled state
  19210. * @see isEnabled
  19211. */
  19212. Light.prototype.setEnabled = function (value) {
  19213. _super.prototype.setEnabled.call(this, value);
  19214. this._resyncMeshes();
  19215. };
  19216. /**
  19217. * Returns the Light associated shadow generator if any.
  19218. * @return the associated shadow generator.
  19219. */
  19220. Light.prototype.getShadowGenerator = function () {
  19221. return this._shadowGenerator;
  19222. };
  19223. /**
  19224. * Returns a Vector3, the absolute light position in the World.
  19225. * @returns the world space position of the light
  19226. */
  19227. Light.prototype.getAbsolutePosition = function () {
  19228. return BABYLON.Vector3.Zero();
  19229. };
  19230. /**
  19231. * Specifies if the light will affect the passed mesh.
  19232. * @param mesh The mesh to test against the light
  19233. * @return true the mesh is affected otherwise, false.
  19234. */
  19235. Light.prototype.canAffectMesh = function (mesh) {
  19236. if (!mesh) {
  19237. return true;
  19238. }
  19239. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19240. return false;
  19241. }
  19242. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19243. return false;
  19244. }
  19245. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19246. return false;
  19247. }
  19248. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19249. return false;
  19250. }
  19251. return true;
  19252. };
  19253. /**
  19254. * Computes and Returns the light World matrix.
  19255. * @returns the world matrix
  19256. */
  19257. Light.prototype.getWorldMatrix = function () {
  19258. this._currentRenderId = this.getScene().getRenderId();
  19259. var worldMatrix = this._getWorldMatrix();
  19260. if (this.parent && this.parent.getWorldMatrix) {
  19261. if (!this._parentedWorldMatrix) {
  19262. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19263. }
  19264. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19265. this._markSyncedWithParent();
  19266. return this._parentedWorldMatrix;
  19267. }
  19268. return worldMatrix;
  19269. };
  19270. /**
  19271. * Sort function to order lights for rendering.
  19272. * @param a First Light object to compare to second.
  19273. * @param b Second Light object to compare first.
  19274. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19275. */
  19276. Light.CompareLightsPriority = function (a, b) {
  19277. //shadow-casting lights have priority over non-shadow-casting lights
  19278. //the renderPrioirty is a secondary sort criterion
  19279. if (a.shadowEnabled !== b.shadowEnabled) {
  19280. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19281. }
  19282. return b.renderPriority - a.renderPriority;
  19283. };
  19284. /**
  19285. * Disposes the light.
  19286. */
  19287. Light.prototype.dispose = function () {
  19288. if (this._shadowGenerator) {
  19289. this._shadowGenerator.dispose();
  19290. this._shadowGenerator = null;
  19291. }
  19292. // Animations
  19293. this.getScene().stopAnimation(this);
  19294. // Remove from meshes
  19295. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19296. var mesh = _a[_i];
  19297. mesh._removeLightSource(this);
  19298. }
  19299. this._uniformBuffer.dispose();
  19300. // Remove from scene
  19301. this.getScene().removeLight(this);
  19302. _super.prototype.dispose.call(this);
  19303. };
  19304. /**
  19305. * Returns the light type ID (integer).
  19306. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19307. */
  19308. Light.prototype.getTypeID = function () {
  19309. return 0;
  19310. };
  19311. /**
  19312. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19313. * @returns the scaled intensity in intensity mode unit
  19314. */
  19315. Light.prototype.getScaledIntensity = function () {
  19316. return this._photometricScale * this.intensity;
  19317. };
  19318. /**
  19319. * Returns a new Light object, named "name", from the current one.
  19320. * @param name The name of the cloned light
  19321. * @returns the new created light
  19322. */
  19323. Light.prototype.clone = function (name) {
  19324. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19325. if (!constructor) {
  19326. return null;
  19327. }
  19328. return BABYLON.SerializationHelper.Clone(constructor, this);
  19329. };
  19330. /**
  19331. * Serializes the current light into a Serialization object.
  19332. * @returns the serialized object.
  19333. */
  19334. Light.prototype.serialize = function () {
  19335. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19336. // Type
  19337. serializationObject.type = this.getTypeID();
  19338. // Parent
  19339. if (this.parent) {
  19340. serializationObject.parentId = this.parent.id;
  19341. }
  19342. // Inclusion / exclusions
  19343. if (this.excludedMeshes.length > 0) {
  19344. serializationObject.excludedMeshesIds = [];
  19345. this.excludedMeshes.forEach(function (mesh) {
  19346. serializationObject.excludedMeshesIds.push(mesh.id);
  19347. });
  19348. }
  19349. if (this.includedOnlyMeshes.length > 0) {
  19350. serializationObject.includedOnlyMeshesIds = [];
  19351. this.includedOnlyMeshes.forEach(function (mesh) {
  19352. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19353. });
  19354. }
  19355. // Animations
  19356. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19357. serializationObject.ranges = this.serializeAnimationRanges();
  19358. return serializationObject;
  19359. };
  19360. /**
  19361. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19362. * This new light is named "name" and added to the passed scene.
  19363. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19364. * @param name The friendly name of the light
  19365. * @param scene The scene the new light will belong to
  19366. * @returns the constructor function
  19367. */
  19368. Light.GetConstructorFromName = function (type, name, scene) {
  19369. switch (type) {
  19370. case 0:
  19371. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19372. case 1:
  19373. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19374. case 2:
  19375. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19376. case 3:
  19377. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19378. }
  19379. return null;
  19380. };
  19381. /**
  19382. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19383. * @param parsedLight The JSON representation of the light
  19384. * @param scene The scene to create the parsed light in
  19385. * @returns the created light after parsing
  19386. */
  19387. Light.Parse = function (parsedLight, scene) {
  19388. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19389. if (!constructor) {
  19390. return null;
  19391. }
  19392. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19393. // Inclusion / exclusions
  19394. if (parsedLight.excludedMeshesIds) {
  19395. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19396. }
  19397. if (parsedLight.includedOnlyMeshesIds) {
  19398. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19399. }
  19400. // Parent
  19401. if (parsedLight.parentId) {
  19402. light._waitingParentId = parsedLight.parentId;
  19403. }
  19404. // Animations
  19405. if (parsedLight.animations) {
  19406. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19407. var parsedAnimation = parsedLight.animations[animationIndex];
  19408. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19409. }
  19410. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19411. }
  19412. if (parsedLight.autoAnimate) {
  19413. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19414. }
  19415. return light;
  19416. };
  19417. Light.prototype._hookArrayForExcluded = function (array) {
  19418. var _this = this;
  19419. var oldPush = array.push;
  19420. array.push = function () {
  19421. var items = [];
  19422. for (var _i = 0; _i < arguments.length; _i++) {
  19423. items[_i] = arguments[_i];
  19424. }
  19425. var result = oldPush.apply(array, items);
  19426. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19427. var item = items_1[_a];
  19428. item._resyncLighSource(_this);
  19429. }
  19430. return result;
  19431. };
  19432. var oldSplice = array.splice;
  19433. array.splice = function (index, deleteCount) {
  19434. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19435. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19436. var item = deleted_1[_i];
  19437. item._resyncLighSource(_this);
  19438. }
  19439. return deleted;
  19440. };
  19441. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19442. var item = array_1[_i];
  19443. item._resyncLighSource(this);
  19444. }
  19445. };
  19446. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19447. var _this = this;
  19448. var oldPush = array.push;
  19449. array.push = function () {
  19450. var items = [];
  19451. for (var _i = 0; _i < arguments.length; _i++) {
  19452. items[_i] = arguments[_i];
  19453. }
  19454. var result = oldPush.apply(array, items);
  19455. _this._resyncMeshes();
  19456. return result;
  19457. };
  19458. var oldSplice = array.splice;
  19459. array.splice = function (index, deleteCount) {
  19460. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19461. _this._resyncMeshes();
  19462. return deleted;
  19463. };
  19464. this._resyncMeshes();
  19465. };
  19466. Light.prototype._resyncMeshes = function () {
  19467. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19468. var mesh = _a[_i];
  19469. mesh._resyncLighSource(this);
  19470. }
  19471. };
  19472. /**
  19473. * Forces the meshes to update their light related information in their rendering used effects
  19474. * @ignore Internal Use Only
  19475. */
  19476. Light.prototype._markMeshesAsLightDirty = function () {
  19477. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19478. var mesh = _a[_i];
  19479. if (mesh._lightSources.indexOf(this) !== -1) {
  19480. mesh._markSubMeshesAsLightDirty();
  19481. }
  19482. }
  19483. };
  19484. /**
  19485. * Recomputes the cached photometric scale if needed.
  19486. */
  19487. Light.prototype._computePhotometricScale = function () {
  19488. this._photometricScale = this._getPhotometricScale();
  19489. this.getScene().resetCachedMaterial();
  19490. };
  19491. /**
  19492. * Returns the Photometric Scale according to the light type and intensity mode.
  19493. */
  19494. Light.prototype._getPhotometricScale = function () {
  19495. var photometricScale = 0.0;
  19496. var lightTypeID = this.getTypeID();
  19497. //get photometric mode
  19498. var photometricMode = this.intensityMode;
  19499. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19500. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19501. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19502. }
  19503. else {
  19504. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19505. }
  19506. }
  19507. //compute photometric scale
  19508. switch (lightTypeID) {
  19509. case Light.LIGHTTYPEID_POINTLIGHT:
  19510. case Light.LIGHTTYPEID_SPOTLIGHT:
  19511. switch (photometricMode) {
  19512. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19513. photometricScale = 1.0 / (4.0 * Math.PI);
  19514. break;
  19515. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19516. photometricScale = 1.0;
  19517. break;
  19518. case Light.INTENSITYMODE_LUMINANCE:
  19519. photometricScale = this.radius * this.radius;
  19520. break;
  19521. }
  19522. break;
  19523. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19524. switch (photometricMode) {
  19525. case Light.INTENSITYMODE_ILLUMINANCE:
  19526. photometricScale = 1.0;
  19527. break;
  19528. case Light.INTENSITYMODE_LUMINANCE:
  19529. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19530. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19531. var apexAngleRadians = this.radius;
  19532. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19533. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19534. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19535. photometricScale = solidAngle;
  19536. break;
  19537. }
  19538. break;
  19539. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19540. // No fall off in hemisperic light.
  19541. photometricScale = 1.0;
  19542. break;
  19543. }
  19544. return photometricScale;
  19545. };
  19546. /**
  19547. * Reorder the light in the scene according to their defined priority.
  19548. * @ignore Internal Use Only
  19549. */
  19550. Light.prototype._reorderLightsInScene = function () {
  19551. var scene = this.getScene();
  19552. if (this._renderPriority != 0) {
  19553. scene.requireLightSorting = true;
  19554. }
  19555. this.getScene().sortLightsByPriority();
  19556. };
  19557. //lightmapMode Consts
  19558. Light._LIGHTMAP_DEFAULT = 0;
  19559. Light._LIGHTMAP_SPECULAR = 1;
  19560. Light._LIGHTMAP_SHADOWSONLY = 2;
  19561. // Intensity Mode Consts
  19562. Light._INTENSITYMODE_AUTOMATIC = 0;
  19563. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19564. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19565. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19566. Light._INTENSITYMODE_LUMINANCE = 4;
  19567. // Light types ids const.
  19568. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19569. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19570. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19571. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19572. __decorate([
  19573. BABYLON.serializeAsColor3()
  19574. ], Light.prototype, "diffuse", void 0);
  19575. __decorate([
  19576. BABYLON.serializeAsColor3()
  19577. ], Light.prototype, "specular", void 0);
  19578. __decorate([
  19579. BABYLON.serialize()
  19580. ], Light.prototype, "intensity", void 0);
  19581. __decorate([
  19582. BABYLON.serialize()
  19583. ], Light.prototype, "range", void 0);
  19584. __decorate([
  19585. BABYLON.serialize()
  19586. ], Light.prototype, "intensityMode", null);
  19587. __decorate([
  19588. BABYLON.serialize()
  19589. ], Light.prototype, "radius", null);
  19590. __decorate([
  19591. BABYLON.serialize()
  19592. ], Light.prototype, "_renderPriority", void 0);
  19593. __decorate([
  19594. BABYLON.expandToProperty("_reorderLightsInScene")
  19595. ], Light.prototype, "renderPriority", void 0);
  19596. __decorate([
  19597. BABYLON.serialize()
  19598. ], Light.prototype, "shadowEnabled", void 0);
  19599. __decorate([
  19600. BABYLON.serialize("excludeWithLayerMask")
  19601. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19602. __decorate([
  19603. BABYLON.serialize("includeOnlyWithLayerMask")
  19604. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19605. __decorate([
  19606. BABYLON.serialize("lightmapMode")
  19607. ], Light.prototype, "_lightmapMode", void 0);
  19608. return Light;
  19609. }(BABYLON.Node));
  19610. BABYLON.Light = Light;
  19611. })(BABYLON || (BABYLON = {}));
  19612. //# sourceMappingURL=babylon.light.js.map
  19613. var BABYLON;
  19614. (function (BABYLON) {
  19615. var Camera = /** @class */ (function (_super) {
  19616. __extends(Camera, _super);
  19617. function Camera(name, position, scene) {
  19618. var _this = _super.call(this, name, scene) || this;
  19619. /**
  19620. * The vector the camera should consider as up.
  19621. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19622. */
  19623. _this.upVector = BABYLON.Vector3.Up();
  19624. _this.orthoLeft = null;
  19625. _this.orthoRight = null;
  19626. _this.orthoBottom = null;
  19627. _this.orthoTop = null;
  19628. /**
  19629. * FOV is set in Radians. (default is 0.8)
  19630. */
  19631. _this.fov = 0.8;
  19632. _this.minZ = 1;
  19633. _this.maxZ = 10000.0;
  19634. _this.inertia = 0.9;
  19635. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19636. _this.isIntermediate = false;
  19637. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19638. /**
  19639. * Restricts the camera to viewing objects with the same layerMask.
  19640. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19641. */
  19642. _this.layerMask = 0x0FFFFFFF;
  19643. /**
  19644. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19645. */
  19646. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19647. // Camera rig members
  19648. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19649. _this._rigCameras = new Array();
  19650. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19651. _this._skipRendering = false;
  19652. _this.customRenderTargets = new Array();
  19653. // Observables
  19654. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19655. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19656. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19657. _this.onRestoreStateObservable = new BABYLON.Observable();
  19658. // Cache
  19659. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19660. _this._projectionMatrix = new BABYLON.Matrix();
  19661. _this._doNotComputeProjectionMatrix = false;
  19662. _this._postProcesses = new Array();
  19663. _this._transformMatrix = BABYLON.Matrix.Zero();
  19664. _this._activeMeshes = new BABYLON.SmartArray(256);
  19665. _this._globalPosition = BABYLON.Vector3.Zero();
  19666. _this._refreshFrustumPlanes = true;
  19667. _this.getScene().addCamera(_this);
  19668. if (!_this.getScene().activeCamera) {
  19669. _this.getScene().activeCamera = _this;
  19670. }
  19671. _this.position = position;
  19672. return _this;
  19673. }
  19674. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19675. get: function () {
  19676. return Camera._PERSPECTIVE_CAMERA;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19682. get: function () {
  19683. return Camera._ORTHOGRAPHIC_CAMERA;
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19689. /**
  19690. * This is the default FOV mode for perspective cameras.
  19691. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19692. *
  19693. */
  19694. get: function () {
  19695. return Camera._FOVMODE_VERTICAL_FIXED;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19701. /**
  19702. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19703. *
  19704. */
  19705. get: function () {
  19706. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19707. },
  19708. enumerable: true,
  19709. configurable: true
  19710. });
  19711. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19712. get: function () {
  19713. return Camera._RIG_MODE_NONE;
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19719. get: function () {
  19720. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19726. get: function () {
  19727. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19728. },
  19729. enumerable: true,
  19730. configurable: true
  19731. });
  19732. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19733. get: function () {
  19734. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19735. },
  19736. enumerable: true,
  19737. configurable: true
  19738. });
  19739. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19740. get: function () {
  19741. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19747. get: function () {
  19748. return Camera._RIG_MODE_VR;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19754. get: function () {
  19755. return Camera._RIG_MODE_WEBVR;
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. /**
  19761. * Store current camera state (fov, position, etc..)
  19762. */
  19763. Camera.prototype.storeState = function () {
  19764. this._stateStored = true;
  19765. this._storedFov = this.fov;
  19766. return this;
  19767. };
  19768. /**
  19769. * Restores the camera state values if it has been stored. You must call storeState() first
  19770. */
  19771. Camera.prototype._restoreStateValues = function () {
  19772. if (!this._stateStored) {
  19773. return false;
  19774. }
  19775. this.fov = this._storedFov;
  19776. return true;
  19777. };
  19778. /**
  19779. * Restored camera state. You must call storeState() first
  19780. */
  19781. Camera.prototype.restoreState = function () {
  19782. if (this._restoreStateValues()) {
  19783. this.onRestoreStateObservable.notifyObservers(this);
  19784. return true;
  19785. }
  19786. return false;
  19787. };
  19788. Camera.prototype.getClassName = function () {
  19789. return "Camera";
  19790. };
  19791. /**
  19792. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19793. */
  19794. Camera.prototype.toString = function (fullDetails) {
  19795. var ret = "Name: " + this.name;
  19796. ret += ", type: " + this.getClassName();
  19797. if (this.animations) {
  19798. for (var i = 0; i < this.animations.length; i++) {
  19799. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19800. }
  19801. }
  19802. if (fullDetails) {
  19803. }
  19804. return ret;
  19805. };
  19806. Object.defineProperty(Camera.prototype, "globalPosition", {
  19807. get: function () {
  19808. return this._globalPosition;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Camera.prototype.getActiveMeshes = function () {
  19814. return this._activeMeshes;
  19815. };
  19816. Camera.prototype.isActiveMesh = function (mesh) {
  19817. return (this._activeMeshes.indexOf(mesh) !== -1);
  19818. };
  19819. //Cache
  19820. Camera.prototype._initCache = function () {
  19821. _super.prototype._initCache.call(this);
  19822. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19823. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19824. this._cache.mode = undefined;
  19825. this._cache.minZ = undefined;
  19826. this._cache.maxZ = undefined;
  19827. this._cache.fov = undefined;
  19828. this._cache.fovMode = undefined;
  19829. this._cache.aspectRatio = undefined;
  19830. this._cache.orthoLeft = undefined;
  19831. this._cache.orthoRight = undefined;
  19832. this._cache.orthoBottom = undefined;
  19833. this._cache.orthoTop = undefined;
  19834. this._cache.renderWidth = undefined;
  19835. this._cache.renderHeight = undefined;
  19836. };
  19837. Camera.prototype._updateCache = function (ignoreParentClass) {
  19838. if (!ignoreParentClass) {
  19839. _super.prototype._updateCache.call(this);
  19840. }
  19841. this._cache.position.copyFrom(this.position);
  19842. this._cache.upVector.copyFrom(this.upVector);
  19843. };
  19844. // Synchronized
  19845. Camera.prototype._isSynchronized = function () {
  19846. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19847. };
  19848. Camera.prototype._isSynchronizedViewMatrix = function () {
  19849. if (!_super.prototype._isSynchronized.call(this))
  19850. return false;
  19851. return this._cache.position.equals(this.position)
  19852. && this._cache.upVector.equals(this.upVector)
  19853. && this.isSynchronizedWithParent();
  19854. };
  19855. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19856. var check = this._cache.mode === this.mode
  19857. && this._cache.minZ === this.minZ
  19858. && this._cache.maxZ === this.maxZ;
  19859. if (!check) {
  19860. return false;
  19861. }
  19862. var engine = this.getEngine();
  19863. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19864. check = this._cache.fov === this.fov
  19865. && this._cache.fovMode === this.fovMode
  19866. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19867. }
  19868. else {
  19869. check = this._cache.orthoLeft === this.orthoLeft
  19870. && this._cache.orthoRight === this.orthoRight
  19871. && this._cache.orthoBottom === this.orthoBottom
  19872. && this._cache.orthoTop === this.orthoTop
  19873. && this._cache.renderWidth === engine.getRenderWidth()
  19874. && this._cache.renderHeight === engine.getRenderHeight();
  19875. }
  19876. return check;
  19877. };
  19878. // Controls
  19879. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19880. };
  19881. Camera.prototype.detachControl = function (element) {
  19882. };
  19883. Camera.prototype.update = function () {
  19884. this._checkInputs();
  19885. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19886. this._updateRigCameras();
  19887. }
  19888. };
  19889. Camera.prototype._checkInputs = function () {
  19890. this.onAfterCheckInputsObservable.notifyObservers(this);
  19891. };
  19892. Object.defineProperty(Camera.prototype, "rigCameras", {
  19893. get: function () {
  19894. return this._rigCameras;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19900. get: function () {
  19901. return this._rigPostProcess;
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19907. // invalidate framebuffer
  19908. if (this._postProcesses.length > 0) {
  19909. this._postProcesses[0].markTextureDirty();
  19910. }
  19911. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19912. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19913. var cam = this._rigCameras[i];
  19914. var rigPostProcess = cam._rigPostProcess;
  19915. // for VR rig, there does not have to be a post process
  19916. if (rigPostProcess) {
  19917. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19918. if (isPass) {
  19919. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19920. cam.isIntermediate = this._postProcesses.length === 0;
  19921. }
  19922. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19923. rigPostProcess.markTextureDirty();
  19924. }
  19925. else {
  19926. cam._postProcesses = this._postProcesses.slice(0);
  19927. }
  19928. }
  19929. };
  19930. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19931. if (insertAt === void 0) { insertAt = null; }
  19932. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19933. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19934. return 0;
  19935. }
  19936. if (insertAt == null || insertAt < 0) {
  19937. this._postProcesses.push(postProcess);
  19938. }
  19939. else {
  19940. this._postProcesses.splice(insertAt, 0, postProcess);
  19941. }
  19942. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19943. return this._postProcesses.indexOf(postProcess);
  19944. };
  19945. Camera.prototype.detachPostProcess = function (postProcess) {
  19946. var idx = this._postProcesses.indexOf(postProcess);
  19947. if (idx !== -1) {
  19948. this._postProcesses.splice(idx, 1);
  19949. }
  19950. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19951. };
  19952. Camera.prototype.getWorldMatrix = function () {
  19953. if (!this._worldMatrix) {
  19954. this._worldMatrix = BABYLON.Matrix.Identity();
  19955. }
  19956. var viewMatrix = this.getViewMatrix();
  19957. viewMatrix.invertToRef(this._worldMatrix);
  19958. return this._worldMatrix;
  19959. };
  19960. Camera.prototype._getViewMatrix = function () {
  19961. return BABYLON.Matrix.Identity();
  19962. };
  19963. Camera.prototype.getViewMatrix = function (force) {
  19964. if (!force && this._isSynchronizedViewMatrix()) {
  19965. return this._computedViewMatrix;
  19966. }
  19967. this.updateCache();
  19968. this._computedViewMatrix = this._getViewMatrix();
  19969. this._currentRenderId = this.getScene().getRenderId();
  19970. this._refreshFrustumPlanes = true;
  19971. if (!this.parent || !this.parent.getWorldMatrix) {
  19972. this._globalPosition.copyFrom(this.position);
  19973. }
  19974. else {
  19975. if (!this._worldMatrix) {
  19976. this._worldMatrix = BABYLON.Matrix.Identity();
  19977. }
  19978. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19979. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19980. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19981. this._computedViewMatrix.invert();
  19982. this._markSyncedWithParent();
  19983. }
  19984. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19985. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19986. }
  19987. this.onViewMatrixChangedObservable.notifyObservers(this);
  19988. return this._computedViewMatrix;
  19989. };
  19990. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19991. this._doNotComputeProjectionMatrix = true;
  19992. if (projection !== undefined) {
  19993. this._projectionMatrix = projection;
  19994. }
  19995. };
  19996. ;
  19997. Camera.prototype.unfreezeProjectionMatrix = function () {
  19998. this._doNotComputeProjectionMatrix = false;
  19999. };
  20000. ;
  20001. Camera.prototype.getProjectionMatrix = function (force) {
  20002. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20003. return this._projectionMatrix;
  20004. }
  20005. // Cache
  20006. this._cache.mode = this.mode;
  20007. this._cache.minZ = this.minZ;
  20008. this._cache.maxZ = this.maxZ;
  20009. // Matrix
  20010. this._refreshFrustumPlanes = true;
  20011. var engine = this.getEngine();
  20012. var scene = this.getScene();
  20013. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20014. this._cache.fov = this.fov;
  20015. this._cache.fovMode = this.fovMode;
  20016. this._cache.aspectRatio = engine.getAspectRatio(this);
  20017. if (this.minZ <= 0) {
  20018. this.minZ = 0.1;
  20019. }
  20020. if (scene.useRightHandedSystem) {
  20021. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20022. }
  20023. else {
  20024. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20025. }
  20026. }
  20027. else {
  20028. var halfWidth = engine.getRenderWidth() / 2.0;
  20029. var halfHeight = engine.getRenderHeight() / 2.0;
  20030. if (scene.useRightHandedSystem) {
  20031. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20032. }
  20033. else {
  20034. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20035. }
  20036. this._cache.orthoLeft = this.orthoLeft;
  20037. this._cache.orthoRight = this.orthoRight;
  20038. this._cache.orthoBottom = this.orthoBottom;
  20039. this._cache.orthoTop = this.orthoTop;
  20040. this._cache.renderWidth = engine.getRenderWidth();
  20041. this._cache.renderHeight = engine.getRenderHeight();
  20042. }
  20043. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20044. return this._projectionMatrix;
  20045. };
  20046. Camera.prototype.getTranformationMatrix = function () {
  20047. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20048. return this._transformMatrix;
  20049. };
  20050. Camera.prototype.updateFrustumPlanes = function () {
  20051. if (!this._refreshFrustumPlanes) {
  20052. return;
  20053. }
  20054. this.getTranformationMatrix();
  20055. if (!this._frustumPlanes) {
  20056. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20057. }
  20058. else {
  20059. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20060. }
  20061. this._refreshFrustumPlanes = false;
  20062. };
  20063. Camera.prototype.isInFrustum = function (target) {
  20064. this.updateFrustumPlanes();
  20065. return target.isInFrustum(this._frustumPlanes);
  20066. };
  20067. Camera.prototype.isCompletelyInFrustum = function (target) {
  20068. this.updateFrustumPlanes();
  20069. return target.isCompletelyInFrustum(this._frustumPlanes);
  20070. };
  20071. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20072. if (length === void 0) { length = 100; }
  20073. if (!transform) {
  20074. transform = this.getWorldMatrix();
  20075. }
  20076. if (!origin) {
  20077. origin = this.position;
  20078. }
  20079. var forward = new BABYLON.Vector3(0, 0, 1);
  20080. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20081. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20082. return new BABYLON.Ray(origin, direction, length);
  20083. };
  20084. Camera.prototype.dispose = function () {
  20085. // Observables
  20086. this.onViewMatrixChangedObservable.clear();
  20087. this.onProjectionMatrixChangedObservable.clear();
  20088. this.onAfterCheckInputsObservable.clear();
  20089. this.onRestoreStateObservable.clear();
  20090. // Inputs
  20091. if (this.inputs) {
  20092. this.inputs.clear();
  20093. }
  20094. // Animations
  20095. this.getScene().stopAnimation(this);
  20096. // Remove from scene
  20097. this.getScene().removeCamera(this);
  20098. while (this._rigCameras.length > 0) {
  20099. var camera = this._rigCameras.pop();
  20100. if (camera) {
  20101. camera.dispose();
  20102. }
  20103. }
  20104. // Postprocesses
  20105. if (this._rigPostProcess) {
  20106. this._rigPostProcess.dispose(this);
  20107. this._rigPostProcess = null;
  20108. this._postProcesses = [];
  20109. }
  20110. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20111. this._rigPostProcess = null;
  20112. this._postProcesses = [];
  20113. }
  20114. else {
  20115. var i = this._postProcesses.length;
  20116. while (--i >= 0) {
  20117. this._postProcesses[i].dispose(this);
  20118. }
  20119. }
  20120. // Render targets
  20121. var i = this.customRenderTargets.length;
  20122. while (--i >= 0) {
  20123. this.customRenderTargets[i].dispose();
  20124. }
  20125. this.customRenderTargets = [];
  20126. // Active Meshes
  20127. this._activeMeshes.dispose();
  20128. _super.prototype.dispose.call(this);
  20129. };
  20130. Object.defineProperty(Camera.prototype, "leftCamera", {
  20131. // ---- Camera rigs section ----
  20132. get: function () {
  20133. if (this._rigCameras.length < 1) {
  20134. return null;
  20135. }
  20136. return this._rigCameras[0];
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Camera.prototype, "rightCamera", {
  20142. get: function () {
  20143. if (this._rigCameras.length < 2) {
  20144. return null;
  20145. }
  20146. return this._rigCameras[1];
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. Camera.prototype.getLeftTarget = function () {
  20152. if (this._rigCameras.length < 1) {
  20153. return null;
  20154. }
  20155. return this._rigCameras[0].getTarget();
  20156. };
  20157. Camera.prototype.getRightTarget = function () {
  20158. if (this._rigCameras.length < 2) {
  20159. return null;
  20160. }
  20161. return this._rigCameras[1].getTarget();
  20162. };
  20163. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20164. if (this.cameraRigMode === mode) {
  20165. return;
  20166. }
  20167. while (this._rigCameras.length > 0) {
  20168. var camera = this._rigCameras.pop();
  20169. if (camera) {
  20170. camera.dispose();
  20171. }
  20172. }
  20173. this.cameraRigMode = mode;
  20174. this._cameraRigParams = {};
  20175. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20176. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20177. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20178. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20179. // create the rig cameras, unless none
  20180. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20181. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20182. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20183. if (leftCamera && rightCamera) {
  20184. this._rigCameras.push(leftCamera);
  20185. this._rigCameras.push(rightCamera);
  20186. }
  20187. }
  20188. switch (this.cameraRigMode) {
  20189. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20190. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20191. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20192. break;
  20193. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20194. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20195. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20196. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20197. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20198. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20199. break;
  20200. case Camera.RIG_MODE_VR:
  20201. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20202. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20203. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20204. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20205. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20206. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20207. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20208. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20209. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20210. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20211. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20212. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20213. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20214. if (metrics.compensateDistortion) {
  20215. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20216. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20217. }
  20218. break;
  20219. case Camera.RIG_MODE_WEBVR:
  20220. if (rigParams.vrDisplay) {
  20221. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20222. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20223. //Left eye
  20224. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20225. this._rigCameras[0].setCameraRigParameter("left", true);
  20226. //leaving this for future reference
  20227. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20228. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20229. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20230. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20231. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20232. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20233. this._rigCameras[0].parent = this;
  20234. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20235. //Right eye
  20236. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20237. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20238. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20239. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20240. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20241. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20242. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20243. this._rigCameras[1].parent = this;
  20244. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20245. if (Camera.UseAlternateWebVRRendering) {
  20246. this._rigCameras[1]._skipRendering = true;
  20247. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20248. }
  20249. }
  20250. break;
  20251. }
  20252. this._cascadePostProcessesToRigCams();
  20253. this.update();
  20254. };
  20255. Camera.prototype._getVRProjectionMatrix = function () {
  20256. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20257. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20258. return this._projectionMatrix;
  20259. };
  20260. Camera.prototype._updateCameraRotationMatrix = function () {
  20261. //Here for WebVR
  20262. };
  20263. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20264. //Here for WebVR
  20265. };
  20266. /**
  20267. * This function MUST be overwritten by the different WebVR cameras available.
  20268. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20269. */
  20270. Camera.prototype._getWebVRProjectionMatrix = function () {
  20271. return BABYLON.Matrix.Identity();
  20272. };
  20273. /**
  20274. * This function MUST be overwritten by the different WebVR cameras available.
  20275. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20276. */
  20277. Camera.prototype._getWebVRViewMatrix = function () {
  20278. return BABYLON.Matrix.Identity();
  20279. };
  20280. Camera.prototype.setCameraRigParameter = function (name, value) {
  20281. if (!this._cameraRigParams) {
  20282. this._cameraRigParams = {};
  20283. }
  20284. this._cameraRigParams[name] = value;
  20285. //provisionnally:
  20286. if (name === "interaxialDistance") {
  20287. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20288. }
  20289. };
  20290. /**
  20291. * needs to be overridden by children so sub has required properties to be copied
  20292. */
  20293. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20294. return null;
  20295. };
  20296. /**
  20297. * May need to be overridden by children
  20298. */
  20299. Camera.prototype._updateRigCameras = function () {
  20300. for (var i = 0; i < this._rigCameras.length; i++) {
  20301. this._rigCameras[i].minZ = this.minZ;
  20302. this._rigCameras[i].maxZ = this.maxZ;
  20303. this._rigCameras[i].fov = this.fov;
  20304. }
  20305. // only update viewport when ANAGLYPH
  20306. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20307. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20308. }
  20309. };
  20310. Camera.prototype._setupInputs = function () {
  20311. };
  20312. Camera.prototype.serialize = function () {
  20313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20314. // Type
  20315. serializationObject.type = this.getClassName();
  20316. // Parent
  20317. if (this.parent) {
  20318. serializationObject.parentId = this.parent.id;
  20319. }
  20320. if (this.inputs) {
  20321. this.inputs.serialize(serializationObject);
  20322. }
  20323. // Animations
  20324. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20325. serializationObject.ranges = this.serializeAnimationRanges();
  20326. return serializationObject;
  20327. };
  20328. Camera.prototype.clone = function (name) {
  20329. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20330. };
  20331. Camera.prototype.getDirection = function (localAxis) {
  20332. var result = BABYLON.Vector3.Zero();
  20333. this.getDirectionToRef(localAxis, result);
  20334. return result;
  20335. };
  20336. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20337. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20338. };
  20339. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20340. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20341. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20342. switch (type) {
  20343. case "ArcRotateCamera":
  20344. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20345. case "DeviceOrientationCamera":
  20346. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20347. case "FollowCamera":
  20348. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20349. case "ArcFollowCamera":
  20350. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20351. case "GamepadCamera":
  20352. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20353. case "TouchCamera":
  20354. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20355. case "VirtualJoysticksCamera":
  20356. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20357. case "WebVRFreeCamera":
  20358. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20359. case "WebVRGamepadCamera":
  20360. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20361. case "VRDeviceOrientationFreeCamera":
  20362. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20363. case "VRDeviceOrientationGamepadCamera":
  20364. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20365. case "AnaglyphArcRotateCamera":
  20366. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20367. case "AnaglyphFreeCamera":
  20368. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20369. case "AnaglyphGamepadCamera":
  20370. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20371. case "AnaglyphUniversalCamera":
  20372. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20373. case "StereoscopicArcRotateCamera":
  20374. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20375. case "StereoscopicFreeCamera":
  20376. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20377. case "StereoscopicGamepadCamera":
  20378. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20379. case "StereoscopicUniversalCamera":
  20380. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20381. case "FreeCamera":// Forcing Universal here
  20382. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20383. default:// Universal Camera is the default value
  20384. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20385. }
  20386. };
  20387. Camera.prototype.computeWorldMatrix = function () {
  20388. return this.getWorldMatrix();
  20389. };
  20390. Camera.Parse = function (parsedCamera, scene) {
  20391. var type = parsedCamera.type;
  20392. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20393. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20394. // Parent
  20395. if (parsedCamera.parentId) {
  20396. camera._waitingParentId = parsedCamera.parentId;
  20397. }
  20398. //If camera has an input manager, let it parse inputs settings
  20399. if (camera.inputs) {
  20400. camera.inputs.parse(parsedCamera);
  20401. camera._setupInputs();
  20402. }
  20403. if (camera.setPosition) {
  20404. camera.position.copyFromFloats(0, 0, 0);
  20405. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20406. }
  20407. // Target
  20408. if (parsedCamera.target) {
  20409. if (camera.setTarget) {
  20410. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20411. }
  20412. }
  20413. // Apply 3d rig, when found
  20414. if (parsedCamera.cameraRigMode) {
  20415. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20416. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20417. }
  20418. // Animations
  20419. if (parsedCamera.animations) {
  20420. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20421. var parsedAnimation = parsedCamera.animations[animationIndex];
  20422. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20423. }
  20424. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20425. }
  20426. if (parsedCamera.autoAnimate) {
  20427. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20428. }
  20429. return camera;
  20430. };
  20431. // Statics
  20432. Camera._PERSPECTIVE_CAMERA = 0;
  20433. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20434. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20435. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20436. Camera._RIG_MODE_NONE = 0;
  20437. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20438. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20439. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20440. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20441. Camera._RIG_MODE_VR = 20;
  20442. Camera._RIG_MODE_WEBVR = 21;
  20443. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20444. Camera.UseAlternateWebVRRendering = false;
  20445. __decorate([
  20446. BABYLON.serializeAsVector3()
  20447. ], Camera.prototype, "position", void 0);
  20448. __decorate([
  20449. BABYLON.serializeAsVector3()
  20450. ], Camera.prototype, "upVector", void 0);
  20451. __decorate([
  20452. BABYLON.serialize()
  20453. ], Camera.prototype, "orthoLeft", void 0);
  20454. __decorate([
  20455. BABYLON.serialize()
  20456. ], Camera.prototype, "orthoRight", void 0);
  20457. __decorate([
  20458. BABYLON.serialize()
  20459. ], Camera.prototype, "orthoBottom", void 0);
  20460. __decorate([
  20461. BABYLON.serialize()
  20462. ], Camera.prototype, "orthoTop", void 0);
  20463. __decorate([
  20464. BABYLON.serialize()
  20465. ], Camera.prototype, "fov", void 0);
  20466. __decorate([
  20467. BABYLON.serialize()
  20468. ], Camera.prototype, "minZ", void 0);
  20469. __decorate([
  20470. BABYLON.serialize()
  20471. ], Camera.prototype, "maxZ", void 0);
  20472. __decorate([
  20473. BABYLON.serialize()
  20474. ], Camera.prototype, "inertia", void 0);
  20475. __decorate([
  20476. BABYLON.serialize()
  20477. ], Camera.prototype, "mode", void 0);
  20478. __decorate([
  20479. BABYLON.serialize()
  20480. ], Camera.prototype, "layerMask", void 0);
  20481. __decorate([
  20482. BABYLON.serialize()
  20483. ], Camera.prototype, "fovMode", void 0);
  20484. __decorate([
  20485. BABYLON.serialize()
  20486. ], Camera.prototype, "cameraRigMode", void 0);
  20487. __decorate([
  20488. BABYLON.serialize()
  20489. ], Camera.prototype, "interaxialDistance", void 0);
  20490. __decorate([
  20491. BABYLON.serialize()
  20492. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20493. return Camera;
  20494. }(BABYLON.Node));
  20495. BABYLON.Camera = Camera;
  20496. })(BABYLON || (BABYLON = {}));
  20497. //# sourceMappingURL=babylon.camera.js.map
  20498. var BABYLON;
  20499. (function (BABYLON) {
  20500. var RenderingManager = /** @class */ (function () {
  20501. function RenderingManager(scene) {
  20502. this._renderingGroups = new Array();
  20503. this._autoClearDepthStencil = {};
  20504. this._customOpaqueSortCompareFn = {};
  20505. this._customAlphaTestSortCompareFn = {};
  20506. this._customTransparentSortCompareFn = {};
  20507. this._renderinGroupInfo = null;
  20508. this._scene = scene;
  20509. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20510. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20511. }
  20512. }
  20513. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20514. if (depth === void 0) { depth = true; }
  20515. if (stencil === void 0) { stencil = true; }
  20516. if (this._depthStencilBufferAlreadyCleaned) {
  20517. return;
  20518. }
  20519. this._scene.getEngine().clear(null, false, depth, stencil);
  20520. this._depthStencilBufferAlreadyCleaned = true;
  20521. };
  20522. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20523. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20524. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20525. var info = null;
  20526. if (observable) {
  20527. if (!this._renderinGroupInfo) {
  20528. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20529. }
  20530. info = this._renderinGroupInfo;
  20531. info.scene = this._scene;
  20532. info.camera = this._scene.activeCamera;
  20533. }
  20534. // Dispatch sprites
  20535. if (renderSprites) {
  20536. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20537. var manager = this._scene.spriteManagers[index];
  20538. this.dispatchSprites(manager);
  20539. }
  20540. }
  20541. // Render
  20542. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20543. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20544. var renderingGroup = this._renderingGroups[index];
  20545. if (!renderingGroup && !observable)
  20546. continue;
  20547. var renderingGroupMask = 0;
  20548. // Fire PRECLEAR stage
  20549. if (observable && info) {
  20550. renderingGroupMask = Math.pow(2, index);
  20551. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20552. info.renderingGroupId = index;
  20553. observable.notifyObservers(info, renderingGroupMask);
  20554. }
  20555. // Clear depth/stencil if needed
  20556. if (RenderingManager.AUTOCLEAR) {
  20557. var autoClear = this._autoClearDepthStencil[index];
  20558. if (autoClear && autoClear.autoClear) {
  20559. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20560. }
  20561. }
  20562. if (observable && info) {
  20563. // Fire PREOPAQUE stage
  20564. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20565. observable.notifyObservers(info, renderingGroupMask);
  20566. // Fire PRETRANSPARENT stage
  20567. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20568. observable.notifyObservers(info, renderingGroupMask);
  20569. }
  20570. if (renderingGroup)
  20571. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20572. // Fire POSTTRANSPARENT stage
  20573. if (observable && info) {
  20574. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20575. observable.notifyObservers(info, renderingGroupMask);
  20576. }
  20577. }
  20578. };
  20579. RenderingManager.prototype.reset = function () {
  20580. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20581. var renderingGroup = this._renderingGroups[index];
  20582. if (renderingGroup) {
  20583. renderingGroup.prepare();
  20584. }
  20585. }
  20586. };
  20587. RenderingManager.prototype.dispose = function () {
  20588. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20589. var renderingGroup = this._renderingGroups[index];
  20590. if (renderingGroup) {
  20591. renderingGroup.dispose();
  20592. }
  20593. }
  20594. this._renderingGroups.length = 0;
  20595. };
  20596. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20597. if (this._renderingGroups[renderingGroupId] === undefined) {
  20598. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20599. }
  20600. };
  20601. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20602. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20603. this._prepareRenderingGroup(renderingGroupId);
  20604. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20605. };
  20606. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20607. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20608. this._prepareRenderingGroup(renderingGroupId);
  20609. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20610. };
  20611. /**
  20612. * @param subMesh The submesh to dispatch
  20613. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20614. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20615. */
  20616. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20617. if (mesh === undefined) {
  20618. mesh = subMesh.getMesh();
  20619. }
  20620. var renderingGroupId = mesh.renderingGroupId || 0;
  20621. this._prepareRenderingGroup(renderingGroupId);
  20622. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20623. };
  20624. /**
  20625. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20626. * This allowed control for front to back rendering or reversly depending of the special needs.
  20627. *
  20628. * @param renderingGroupId The rendering group id corresponding to its index
  20629. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20630. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20631. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20632. */
  20633. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20634. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20635. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20636. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20637. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20638. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20639. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20640. if (this._renderingGroups[renderingGroupId]) {
  20641. var group = this._renderingGroups[renderingGroupId];
  20642. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20643. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20644. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20645. }
  20646. };
  20647. /**
  20648. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20649. *
  20650. * @param renderingGroupId The rendering group id corresponding to its index
  20651. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20652. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20653. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20654. */
  20655. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20656. if (depth === void 0) { depth = true; }
  20657. if (stencil === void 0) { stencil = true; }
  20658. this._autoClearDepthStencil[renderingGroupId] = {
  20659. autoClear: autoClearDepthStencil,
  20660. depth: depth,
  20661. stencil: stencil
  20662. };
  20663. };
  20664. /**
  20665. * The max id used for rendering groups (not included)
  20666. */
  20667. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20668. /**
  20669. * The min id used for rendering groups (included)
  20670. */
  20671. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20672. /**
  20673. * Used to globally prevent autoclearing scenes.
  20674. */
  20675. RenderingManager.AUTOCLEAR = true;
  20676. return RenderingManager;
  20677. }());
  20678. BABYLON.RenderingManager = RenderingManager;
  20679. })(BABYLON || (BABYLON = {}));
  20680. //# sourceMappingURL=babylon.renderingManager.js.map
  20681. var BABYLON;
  20682. (function (BABYLON) {
  20683. var RenderingGroup = /** @class */ (function () {
  20684. /**
  20685. * Creates a new rendering group.
  20686. * @param index The rendering group index
  20687. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20688. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20689. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20690. */
  20691. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20692. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20693. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20694. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20695. this.index = index;
  20696. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20697. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20698. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20699. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20700. this._particleSystems = new BABYLON.SmartArray(256);
  20701. this._spriteManagers = new BABYLON.SmartArray(256);
  20702. this._edgesRenderers = new BABYLON.SmartArray(16);
  20703. this._scene = scene;
  20704. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20705. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20706. this.transparentSortCompareFn = transparentSortCompareFn;
  20707. }
  20708. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20709. /**
  20710. * Set the opaque sort comparison function.
  20711. * If null the sub meshes will be render in the order they were created
  20712. */
  20713. set: function (value) {
  20714. this._opaqueSortCompareFn = value;
  20715. if (value) {
  20716. this._renderOpaque = this.renderOpaqueSorted;
  20717. }
  20718. else {
  20719. this._renderOpaque = RenderingGroup.renderUnsorted;
  20720. }
  20721. },
  20722. enumerable: true,
  20723. configurable: true
  20724. });
  20725. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20726. /**
  20727. * Set the alpha test sort comparison function.
  20728. * If null the sub meshes will be render in the order they were created
  20729. */
  20730. set: function (value) {
  20731. this._alphaTestSortCompareFn = value;
  20732. if (value) {
  20733. this._renderAlphaTest = this.renderAlphaTestSorted;
  20734. }
  20735. else {
  20736. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20737. }
  20738. },
  20739. enumerable: true,
  20740. configurable: true
  20741. });
  20742. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20743. /**
  20744. * Set the transparent sort comparison function.
  20745. * If null the sub meshes will be render in the order they were created
  20746. */
  20747. set: function (value) {
  20748. if (value) {
  20749. this._transparentSortCompareFn = value;
  20750. }
  20751. else {
  20752. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20753. }
  20754. this._renderTransparent = this.renderTransparentSorted;
  20755. },
  20756. enumerable: true,
  20757. configurable: true
  20758. });
  20759. /**
  20760. * Render all the sub meshes contained in the group.
  20761. * @param customRenderFunction Used to override the default render behaviour of the group.
  20762. * @returns true if rendered some submeshes.
  20763. */
  20764. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20765. if (customRenderFunction) {
  20766. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20767. return;
  20768. }
  20769. var engine = this._scene.getEngine();
  20770. // Depth only
  20771. if (this._depthOnlySubMeshes.length !== 0) {
  20772. engine.setColorWrite(false);
  20773. this._renderAlphaTest(this._depthOnlySubMeshes);
  20774. engine.setColorWrite(true);
  20775. }
  20776. // Opaque
  20777. if (this._opaqueSubMeshes.length !== 0) {
  20778. this._renderOpaque(this._opaqueSubMeshes);
  20779. }
  20780. // Alpha test
  20781. if (this._alphaTestSubMeshes.length !== 0) {
  20782. this._renderAlphaTest(this._alphaTestSubMeshes);
  20783. }
  20784. var stencilState = engine.getStencilBuffer();
  20785. engine.setStencilBuffer(false);
  20786. // Sprites
  20787. if (renderSprites) {
  20788. this._renderSprites();
  20789. }
  20790. // Particles
  20791. if (renderParticles) {
  20792. this._renderParticles(activeMeshes);
  20793. }
  20794. if (this.onBeforeTransparentRendering) {
  20795. this.onBeforeTransparentRendering();
  20796. }
  20797. // Transparent
  20798. if (this._transparentSubMeshes.length !== 0) {
  20799. this._renderTransparent(this._transparentSubMeshes);
  20800. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20801. }
  20802. // Set back stencil to false in case it changes before the edge renderer.
  20803. engine.setStencilBuffer(false);
  20804. // Edges
  20805. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20806. this._edgesRenderers.data[edgesRendererIndex].render();
  20807. }
  20808. // Restore Stencil state.
  20809. engine.setStencilBuffer(stencilState);
  20810. };
  20811. /**
  20812. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20813. * @param subMeshes The submeshes to render
  20814. */
  20815. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20816. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20817. };
  20818. /**
  20819. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20820. * @param subMeshes The submeshes to render
  20821. */
  20822. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20823. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20824. };
  20825. /**
  20826. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20827. * @param subMeshes The submeshes to render
  20828. */
  20829. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20830. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20831. };
  20832. /**
  20833. * Renders the submeshes in a specified order.
  20834. * @param subMeshes The submeshes to sort before render
  20835. * @param sortCompareFn The comparison function use to sort
  20836. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20837. * @param transparent Specifies to activate blending if true
  20838. */
  20839. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20840. var subIndex = 0;
  20841. var subMesh;
  20842. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20843. for (; subIndex < subMeshes.length; subIndex++) {
  20844. subMesh = subMeshes.data[subIndex];
  20845. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20846. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20847. }
  20848. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20849. if (sortCompareFn) {
  20850. sortedArray.sort(sortCompareFn);
  20851. }
  20852. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20853. subMesh = sortedArray[subIndex];
  20854. if (transparent) {
  20855. var material = subMesh.getMaterial();
  20856. if (material && material.needDepthPrePass) {
  20857. var engine = material.getScene().getEngine();
  20858. engine.setColorWrite(false);
  20859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20860. subMesh.render(false);
  20861. engine.setColorWrite(true);
  20862. }
  20863. }
  20864. subMesh.render(transparent);
  20865. }
  20866. };
  20867. /**
  20868. * Renders the submeshes in the order they were dispatched (no sort applied).
  20869. * @param subMeshes The submeshes to render
  20870. */
  20871. RenderingGroup.renderUnsorted = function (subMeshes) {
  20872. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20873. var submesh = subMeshes.data[subIndex];
  20874. submesh.render(false);
  20875. }
  20876. };
  20877. /**
  20878. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20879. * are rendered back to front if in the same alpha index.
  20880. *
  20881. * @param a The first submesh
  20882. * @param b The second submesh
  20883. * @returns The result of the comparison
  20884. */
  20885. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20886. // Alpha index first
  20887. if (a._alphaIndex > b._alphaIndex) {
  20888. return 1;
  20889. }
  20890. if (a._alphaIndex < b._alphaIndex) {
  20891. return -1;
  20892. }
  20893. // Then distance to camera
  20894. return RenderingGroup.backToFrontSortCompare(a, b);
  20895. };
  20896. /**
  20897. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20898. * are rendered back to front.
  20899. *
  20900. * @param a The first submesh
  20901. * @param b The second submesh
  20902. * @returns The result of the comparison
  20903. */
  20904. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20905. // Then distance to camera
  20906. if (a._distanceToCamera < b._distanceToCamera) {
  20907. return 1;
  20908. }
  20909. if (a._distanceToCamera > b._distanceToCamera) {
  20910. return -1;
  20911. }
  20912. return 0;
  20913. };
  20914. /**
  20915. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20916. * are rendered front to back (prevent overdraw).
  20917. *
  20918. * @param a The first submesh
  20919. * @param b The second submesh
  20920. * @returns The result of the comparison
  20921. */
  20922. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20923. // Then distance to camera
  20924. if (a._distanceToCamera < b._distanceToCamera) {
  20925. return -1;
  20926. }
  20927. if (a._distanceToCamera > b._distanceToCamera) {
  20928. return 1;
  20929. }
  20930. return 0;
  20931. };
  20932. /**
  20933. * Resets the different lists of submeshes to prepare a new frame.
  20934. */
  20935. RenderingGroup.prototype.prepare = function () {
  20936. this._opaqueSubMeshes.reset();
  20937. this._transparentSubMeshes.reset();
  20938. this._alphaTestSubMeshes.reset();
  20939. this._depthOnlySubMeshes.reset();
  20940. this._particleSystems.reset();
  20941. this._spriteManagers.reset();
  20942. this._edgesRenderers.reset();
  20943. };
  20944. RenderingGroup.prototype.dispose = function () {
  20945. this._opaqueSubMeshes.dispose();
  20946. this._transparentSubMeshes.dispose();
  20947. this._alphaTestSubMeshes.dispose();
  20948. this._depthOnlySubMeshes.dispose();
  20949. this._particleSystems.dispose();
  20950. this._spriteManagers.dispose();
  20951. this._edgesRenderers.dispose();
  20952. };
  20953. /**
  20954. * Inserts the submesh in its correct queue depending on its material.
  20955. * @param subMesh The submesh to dispatch
  20956. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20957. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20958. */
  20959. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20960. // Get mesh and materials if not provided
  20961. if (mesh === undefined) {
  20962. mesh = subMesh.getMesh();
  20963. }
  20964. if (material === undefined) {
  20965. material = subMesh.getMaterial();
  20966. }
  20967. if (material === null || material === undefined) {
  20968. return;
  20969. }
  20970. if (material.needAlphaBlendingForMesh(mesh)) {
  20971. this._transparentSubMeshes.push(subMesh);
  20972. }
  20973. else if (material.needAlphaTesting()) {
  20974. if (material.needDepthPrePass) {
  20975. this._depthOnlySubMeshes.push(subMesh);
  20976. }
  20977. this._alphaTestSubMeshes.push(subMesh);
  20978. }
  20979. else {
  20980. if (material.needDepthPrePass) {
  20981. this._depthOnlySubMeshes.push(subMesh);
  20982. }
  20983. this._opaqueSubMeshes.push(subMesh); // Opaque
  20984. }
  20985. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20986. this._edgesRenderers.push(mesh._edgesRenderer);
  20987. }
  20988. };
  20989. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20990. this._spriteManagers.push(spriteManager);
  20991. };
  20992. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20993. this._particleSystems.push(particleSystem);
  20994. };
  20995. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20996. if (this._particleSystems.length === 0) {
  20997. return;
  20998. }
  20999. // Particles
  21000. var activeCamera = this._scene.activeCamera;
  21001. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21002. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21003. var particleSystem = this._particleSystems.data[particleIndex];
  21004. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21005. continue;
  21006. }
  21007. var emitter = particleSystem.emitter;
  21008. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21009. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21010. }
  21011. }
  21012. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21013. };
  21014. RenderingGroup.prototype._renderSprites = function () {
  21015. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21016. return;
  21017. }
  21018. // Sprites
  21019. var activeCamera = this._scene.activeCamera;
  21020. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21021. for (var id = 0; id < this._spriteManagers.length; id++) {
  21022. var spriteManager = this._spriteManagers.data[id];
  21023. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21024. spriteManager.render();
  21025. }
  21026. }
  21027. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21028. };
  21029. return RenderingGroup;
  21030. }());
  21031. BABYLON.RenderingGroup = RenderingGroup;
  21032. })(BABYLON || (BABYLON = {}));
  21033. //# sourceMappingURL=babylon.renderingGroup.js.map
  21034. var BABYLON;
  21035. (function (BABYLON) {
  21036. var ClickInfo = /** @class */ (function () {
  21037. function ClickInfo() {
  21038. this._singleClick = false;
  21039. this._doubleClick = false;
  21040. this._hasSwiped = false;
  21041. this._ignore = false;
  21042. }
  21043. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21044. get: function () {
  21045. return this._singleClick;
  21046. },
  21047. set: function (b) {
  21048. this._singleClick = b;
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21054. get: function () {
  21055. return this._doubleClick;
  21056. },
  21057. set: function (b) {
  21058. this._doubleClick = b;
  21059. },
  21060. enumerable: true,
  21061. configurable: true
  21062. });
  21063. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21064. get: function () {
  21065. return this._hasSwiped;
  21066. },
  21067. set: function (b) {
  21068. this._hasSwiped = b;
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21074. get: function () {
  21075. return this._ignore;
  21076. },
  21077. set: function (b) {
  21078. this._ignore = b;
  21079. },
  21080. enumerable: true,
  21081. configurable: true
  21082. });
  21083. return ClickInfo;
  21084. }());
  21085. /**
  21086. * This class is used by the onRenderingGroupObservable
  21087. */
  21088. var RenderingGroupInfo = /** @class */ (function () {
  21089. function RenderingGroupInfo() {
  21090. }
  21091. /**
  21092. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21093. * This stage will be fired no matter what
  21094. */
  21095. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21096. /**
  21097. * Called before opaque object are rendered.
  21098. * This stage will be fired only if there's 3D Opaque content to render
  21099. */
  21100. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21101. /**
  21102. * Called after the opaque objects are rendered and before the transparent ones
  21103. * This stage will be fired only if there's 3D transparent content to render
  21104. */
  21105. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21106. /**
  21107. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21108. * This stage will be fired no matter what
  21109. */
  21110. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21111. return RenderingGroupInfo;
  21112. }());
  21113. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21114. /**
  21115. * Represents a scene to be rendered by the engine.
  21116. * @see http://doc.babylonjs.com/page.php?p=21911
  21117. */
  21118. var Scene = /** @class */ (function () {
  21119. /**
  21120. * @constructor
  21121. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21122. */
  21123. function Scene(engine) {
  21124. // Members
  21125. this.autoClear = true;
  21126. this.autoClearDepthAndStencil = true;
  21127. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21128. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21129. this.forceWireframe = false;
  21130. this._forcePointsCloud = false;
  21131. this.forceShowBoundingBoxes = false;
  21132. this.animationsEnabled = true;
  21133. this.useConstantAnimationDeltaTime = false;
  21134. this.constantlyUpdateMeshUnderPointer = false;
  21135. this.hoverCursor = "pointer";
  21136. this.defaultCursor = "";
  21137. /**
  21138. * This is used to call preventDefault() on pointer down
  21139. * in order to block unwanted artifacts like system double clicks
  21140. */
  21141. this.preventDefaultOnPointerDown = true;
  21142. // Metadata
  21143. this.metadata = null;
  21144. /**
  21145. * An event triggered when the scene is disposed.
  21146. * @type {BABYLON.Observable}
  21147. */
  21148. this.onDisposeObservable = new BABYLON.Observable();
  21149. /**
  21150. * An event triggered before rendering the scene (right after animations and physics)
  21151. * @type {BABYLON.Observable}
  21152. */
  21153. this.onBeforeRenderObservable = new BABYLON.Observable();
  21154. /**
  21155. * An event triggered after rendering the scene
  21156. * @type {BABYLON.Observable}
  21157. */
  21158. this.onAfterRenderObservable = new BABYLON.Observable();
  21159. /**
  21160. * An event triggered before animating the scene
  21161. * @type {BABYLON.Observable}
  21162. */
  21163. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21164. /**
  21165. * An event triggered after animations processing
  21166. * @type {BABYLON.Observable}
  21167. */
  21168. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21169. /**
  21170. * An event triggered before draw calls are ready to be sent
  21171. * @type {BABYLON.Observable}
  21172. */
  21173. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21174. /**
  21175. * An event triggered after draw calls have been sent
  21176. * @type {BABYLON.Observable}
  21177. */
  21178. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21179. /**
  21180. * An event triggered when physic simulation is about to be run
  21181. * @type {BABYLON.Observable}
  21182. */
  21183. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21184. /**
  21185. * An event triggered when physic simulation has been done
  21186. * @type {BABYLON.Observable}
  21187. */
  21188. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21189. /**
  21190. * An event triggered when the scene is ready
  21191. * @type {BABYLON.Observable}
  21192. */
  21193. this.onReadyObservable = new BABYLON.Observable();
  21194. /**
  21195. * An event triggered before rendering a camera
  21196. * @type {BABYLON.Observable}
  21197. */
  21198. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21199. /**
  21200. * An event triggered after rendering a camera
  21201. * @type {BABYLON.Observable}
  21202. */
  21203. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21204. /**
  21205. * An event triggered when active meshes evaluation is about to start
  21206. * @type {BABYLON.Observable}
  21207. */
  21208. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21209. /**
  21210. * An event triggered when active meshes evaluation is done
  21211. * @type {BABYLON.Observable}
  21212. */
  21213. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21214. /**
  21215. * An event triggered when particles rendering is about to start
  21216. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21217. * @type {BABYLON.Observable}
  21218. */
  21219. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21220. /**
  21221. * An event triggered when particles rendering is done
  21222. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21223. * @type {BABYLON.Observable}
  21224. */
  21225. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21226. /**
  21227. * An event triggered when sprites rendering is about to start
  21228. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21229. * @type {BABYLON.Observable}
  21230. */
  21231. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21232. /**
  21233. * An event triggered when sprites rendering is done
  21234. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21235. * @type {BABYLON.Observable}
  21236. */
  21237. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21238. /**
  21239. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21240. * @type {BABYLON.Observable}
  21241. */
  21242. this.onDataLoadedObservable = new BABYLON.Observable();
  21243. /**
  21244. * An event triggered when a camera is created
  21245. * @type {BABYLON.Observable}
  21246. */
  21247. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21248. /**
  21249. * An event triggered when a camera is removed
  21250. * @type {BABYLON.Observable}
  21251. */
  21252. this.onCameraRemovedObservable = new BABYLON.Observable();
  21253. /**
  21254. * An event triggered when a light is created
  21255. * @type {BABYLON.Observable}
  21256. */
  21257. this.onNewLightAddedObservable = new BABYLON.Observable();
  21258. /**
  21259. * An event triggered when a light is removed
  21260. * @type {BABYLON.Observable}
  21261. */
  21262. this.onLightRemovedObservable = new BABYLON.Observable();
  21263. /**
  21264. * An event triggered when a geometry is created
  21265. * @type {BABYLON.Observable}
  21266. */
  21267. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21268. /**
  21269. * An event triggered when a geometry is removed
  21270. * @type {BABYLON.Observable}
  21271. */
  21272. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21273. /**
  21274. * An event triggered when a transform node is created
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered when a transform node is removed
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered when a mesh is created
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when a mesh is removed
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onMeshRemovedObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when render targets are about to be rendered
  21295. * Can happen multiple times per frame.
  21296. * @type {BABYLON.Observable}
  21297. */
  21298. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21299. /**
  21300. * An event triggered when render targets were rendered.
  21301. * Can happen multiple times per frame.
  21302. * @type {BABYLON.Observable}
  21303. */
  21304. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21305. /**
  21306. * An event triggered before calculating deterministic simulation step
  21307. * @type {BABYLON.Observable}
  21308. */
  21309. this.onBeforeStepObservable = new BABYLON.Observable();
  21310. /**
  21311. * An event triggered after calculating deterministic simulation step
  21312. * @type {BABYLON.Observable}
  21313. */
  21314. this.onAfterStepObservable = new BABYLON.Observable();
  21315. /**
  21316. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21317. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21318. * 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)
  21319. */
  21320. this.onRenderingGroupObservable = new BABYLON.Observable();
  21321. // Animations
  21322. this.animations = [];
  21323. /**
  21324. * 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).
  21325. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21326. */
  21327. this.onPrePointerObservable = new BABYLON.Observable();
  21328. /**
  21329. * Observable event triggered each time an input event is received from the rendering canvas
  21330. */
  21331. this.onPointerObservable = new BABYLON.Observable();
  21332. this._meshPickProceed = false;
  21333. this._currentPickResult = null;
  21334. this._previousPickResult = null;
  21335. this._totalPointersPressed = 0;
  21336. this._doubleClickOccured = false;
  21337. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21338. this.cameraToUseForPointers = null;
  21339. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21340. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21341. this._startingPointerTime = 0;
  21342. this._previousStartingPointerTime = 0;
  21343. // Deterministic lockstep
  21344. this._timeAccumulator = 0;
  21345. this._currentStepId = 0;
  21346. this._currentInternalStep = 0;
  21347. // Keyboard
  21348. /**
  21349. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21350. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21351. */
  21352. this.onPreKeyboardObservable = new BABYLON.Observable();
  21353. /**
  21354. * Observable event triggered each time an keyboard event is received from the hosting window
  21355. */
  21356. this.onKeyboardObservable = new BABYLON.Observable();
  21357. // Coordinate system
  21358. /**
  21359. * use right-handed coordinate system on this scene.
  21360. * @type {boolean}
  21361. */
  21362. this._useRightHandedSystem = false;
  21363. // Fog
  21364. this._fogEnabled = true;
  21365. this._fogMode = Scene.FOGMODE_NONE;
  21366. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21367. this.fogDensity = 0.1;
  21368. this.fogStart = 0;
  21369. this.fogEnd = 1000.0;
  21370. // Lights
  21371. /**
  21372. * is shadow enabled on this scene.
  21373. * @type {boolean}
  21374. */
  21375. this._shadowsEnabled = true;
  21376. /**
  21377. * is light enabled on this scene.
  21378. * @type {boolean}
  21379. */
  21380. this._lightsEnabled = true;
  21381. /**
  21382. * All of the lights added to this scene.
  21383. * @see BABYLON.Light
  21384. * @type {BABYLON.Light[]}
  21385. */
  21386. this.lights = new Array();
  21387. // Cameras
  21388. /** All of the cameras added to this scene. */
  21389. this.cameras = new Array();
  21390. /** All of the active cameras added to this scene. */
  21391. this.activeCameras = new Array();
  21392. // Meshes
  21393. /**
  21394. * All of the tranform nodes added to this scene.
  21395. * @see BABYLON.TransformNode
  21396. * @type {BABYLON.TransformNode[]}
  21397. */
  21398. this.transformNodes = new Array();
  21399. /**
  21400. * All of the (abstract) meshes added to this scene.
  21401. * @see BABYLON.AbstractMesh
  21402. * @type {BABYLON.AbstractMesh[]}
  21403. */
  21404. this.meshes = new Array();
  21405. /**
  21406. * All of the animation groups added to this scene.
  21407. * @see BABYLON.AnimationGroup
  21408. * @type {BABYLON.AnimationGroup[]}
  21409. */
  21410. this.animationGroups = new Array();
  21411. // Geometries
  21412. this._geometries = new Array();
  21413. this.materials = new Array();
  21414. this.multiMaterials = new Array();
  21415. // Textures
  21416. this._texturesEnabled = true;
  21417. this.textures = new Array();
  21418. // Particles
  21419. this.particlesEnabled = true;
  21420. this.particleSystems = new Array();
  21421. // Sprites
  21422. this.spritesEnabled = true;
  21423. this.spriteManagers = new Array();
  21424. /**
  21425. * The list of layers (background and foreground) of the scene.
  21426. */
  21427. this.layers = new Array();
  21428. /**
  21429. * The list of effect layers (highlights/glow) contained in the scene.
  21430. */
  21431. this.effectLayers = new Array();
  21432. // Skeletons
  21433. this._skeletonsEnabled = true;
  21434. this.skeletons = new Array();
  21435. // Morph targets
  21436. this.morphTargetManagers = new Array();
  21437. // Lens flares
  21438. this.lensFlaresEnabled = true;
  21439. this.lensFlareSystems = new Array();
  21440. // Collisions
  21441. this.collisionsEnabled = true;
  21442. /** Defines the gravity applied to this scene */
  21443. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21444. // Postprocesses
  21445. this.postProcesses = new Array();
  21446. this.postProcessesEnabled = true;
  21447. // Customs render targets
  21448. this.renderTargetsEnabled = true;
  21449. this.dumpNextRenderTargets = false;
  21450. this.customRenderTargets = new Array();
  21451. // Imported meshes
  21452. this.importedMeshesFiles = new Array();
  21453. // Probes
  21454. this.probesEnabled = true;
  21455. this.reflectionProbes = new Array();
  21456. this._actionManagers = new Array();
  21457. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21458. // Procedural textures
  21459. this.proceduralTexturesEnabled = true;
  21460. this._proceduralTextures = new Array();
  21461. this.soundTracks = new Array();
  21462. this._audioEnabled = true;
  21463. this._headphone = false;
  21464. // Performance counters
  21465. this._totalVertices = new BABYLON.PerfCounter();
  21466. this._activeIndices = new BABYLON.PerfCounter();
  21467. this._activeParticles = new BABYLON.PerfCounter();
  21468. this._activeBones = new BABYLON.PerfCounter();
  21469. this._animationTime = 0;
  21470. this.animationTimeScale = 1;
  21471. this._renderId = 0;
  21472. this._executeWhenReadyTimeoutId = -1;
  21473. this._intermediateRendering = false;
  21474. this._viewUpdateFlag = -1;
  21475. this._projectionUpdateFlag = -1;
  21476. this._alternateViewUpdateFlag = -1;
  21477. this._alternateProjectionUpdateFlag = -1;
  21478. this._toBeDisposed = new BABYLON.SmartArray(256);
  21479. this._activeRequests = new Array();
  21480. this._pendingData = new Array();
  21481. this._isDisposed = false;
  21482. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21483. this._activeMeshes = new BABYLON.SmartArray(256);
  21484. this._processedMaterials = new BABYLON.SmartArray(256);
  21485. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21486. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21487. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21488. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21489. this._activeAnimatables = new Array();
  21490. this._transformMatrix = BABYLON.Matrix.Zero();
  21491. this._useAlternateCameraConfiguration = false;
  21492. this._alternateRendering = false;
  21493. this.requireLightSorting = false;
  21494. this._depthRenderer = {};
  21495. this._activeMeshesFrozen = false;
  21496. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21497. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21498. this._engine.scenes.push(this);
  21499. this._uid = null;
  21500. this._renderingManager = new BABYLON.RenderingManager(this);
  21501. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21502. if (BABYLON.OutlineRenderer) {
  21503. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21504. }
  21505. if (BABYLON.Tools.IsWindowObjectExist()) {
  21506. this.attachControl();
  21507. }
  21508. //simplification queue
  21509. if (BABYLON.SimplificationQueue) {
  21510. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21511. }
  21512. //collision coordinator initialization. For now legacy per default.
  21513. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21514. // Uniform Buffer
  21515. this._createUbo();
  21516. // Default Image processing definition.
  21517. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21518. }
  21519. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21520. /** The fog is deactivated */
  21521. get: function () {
  21522. return Scene._FOGMODE_NONE;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21528. /** The fog density is following an exponential function */
  21529. get: function () {
  21530. return Scene._FOGMODE_EXP;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21536. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21537. get: function () {
  21538. return Scene._FOGMODE_EXP2;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21544. /** The fog density is following a linear function. */
  21545. get: function () {
  21546. return Scene._FOGMODE_LINEAR;
  21547. },
  21548. enumerable: true,
  21549. configurable: true
  21550. });
  21551. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21552. /**
  21553. * Texture used in all pbr material as the reflection texture.
  21554. * As in the majority of the scene they are the same (exception for multi room and so on),
  21555. * this is easier to reference from here than from all the materials.
  21556. */
  21557. get: function () {
  21558. return this._environmentTexture;
  21559. },
  21560. /**
  21561. * Texture used in all pbr material as the reflection texture.
  21562. * As in the majority of the scene they are the same (exception for multi room and so on),
  21563. * this is easier to set here than in all the materials.
  21564. */
  21565. set: function (value) {
  21566. if (this._environmentTexture === value) {
  21567. return;
  21568. }
  21569. this._environmentTexture = value;
  21570. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21576. /**
  21577. * Default image processing configuration used either in the rendering
  21578. * Forward main pass or through the imageProcessingPostProcess if present.
  21579. * As in the majority of the scene they are the same (exception for multi camera),
  21580. * this is easier to reference from here than from all the materials and post process.
  21581. *
  21582. * No setter as we it is a shared configuration, you can set the values instead.
  21583. */
  21584. get: function () {
  21585. return this._imageProcessingConfiguration;
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21591. get: function () {
  21592. return this._forcePointsCloud;
  21593. },
  21594. set: function (value) {
  21595. if (this._forcePointsCloud === value) {
  21596. return;
  21597. }
  21598. this._forcePointsCloud = value;
  21599. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. Object.defineProperty(Scene.prototype, "onDispose", {
  21605. /** A function to be executed when this scene is disposed. */
  21606. set: function (callback) {
  21607. if (this._onDisposeObserver) {
  21608. this.onDisposeObservable.remove(this._onDisposeObserver);
  21609. }
  21610. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Scene.prototype, "beforeRender", {
  21616. /** A function to be executed before rendering this scene */
  21617. set: function (callback) {
  21618. if (this._onBeforeRenderObserver) {
  21619. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21620. }
  21621. if (callback) {
  21622. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21623. }
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Object.defineProperty(Scene.prototype, "afterRender", {
  21629. /** A function to be executed after rendering this scene */
  21630. set: function (callback) {
  21631. if (this._onAfterRenderObserver) {
  21632. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21633. }
  21634. if (callback) {
  21635. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21636. }
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21642. set: function (callback) {
  21643. if (this._onBeforeCameraRenderObserver) {
  21644. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21645. }
  21646. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21652. set: function (callback) {
  21653. if (this._onAfterCameraRenderObserver) {
  21654. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21655. }
  21656. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21662. get: function () {
  21663. if (!this._gamepadManager) {
  21664. this._gamepadManager = new BABYLON.GamepadManager(this);
  21665. }
  21666. return this._gamepadManager;
  21667. },
  21668. enumerable: true,
  21669. configurable: true
  21670. });
  21671. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21672. get: function () {
  21673. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21679. get: function () {
  21680. return this._useRightHandedSystem;
  21681. },
  21682. set: function (value) {
  21683. if (this._useRightHandedSystem === value) {
  21684. return;
  21685. }
  21686. this._useRightHandedSystem = value;
  21687. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Scene.prototype.setStepId = function (newStepId) {
  21693. this._currentStepId = newStepId;
  21694. };
  21695. ;
  21696. Scene.prototype.getStepId = function () {
  21697. return this._currentStepId;
  21698. };
  21699. ;
  21700. Scene.prototype.getInternalStep = function () {
  21701. return this._currentInternalStep;
  21702. };
  21703. ;
  21704. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21705. get: function () {
  21706. return this._fogEnabled;
  21707. },
  21708. /**
  21709. * is fog enabled on this scene.
  21710. */
  21711. set: function (value) {
  21712. if (this._fogEnabled === value) {
  21713. return;
  21714. }
  21715. this._fogEnabled = value;
  21716. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21717. },
  21718. enumerable: true,
  21719. configurable: true
  21720. });
  21721. Object.defineProperty(Scene.prototype, "fogMode", {
  21722. get: function () {
  21723. return this._fogMode;
  21724. },
  21725. set: function (value) {
  21726. if (this._fogMode === value) {
  21727. return;
  21728. }
  21729. this._fogMode = value;
  21730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21736. get: function () {
  21737. return this._shadowsEnabled;
  21738. },
  21739. set: function (value) {
  21740. if (this._shadowsEnabled === value) {
  21741. return;
  21742. }
  21743. this._shadowsEnabled = value;
  21744. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21745. },
  21746. enumerable: true,
  21747. configurable: true
  21748. });
  21749. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21750. get: function () {
  21751. return this._lightsEnabled;
  21752. },
  21753. set: function (value) {
  21754. if (this._lightsEnabled === value) {
  21755. return;
  21756. }
  21757. this._lightsEnabled = value;
  21758. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21759. },
  21760. enumerable: true,
  21761. configurable: true
  21762. });
  21763. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21764. /** The default material used on meshes when no material is affected */
  21765. get: function () {
  21766. if (!this._defaultMaterial) {
  21767. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21768. }
  21769. return this._defaultMaterial;
  21770. },
  21771. /** The default material used on meshes when no material is affected */
  21772. set: function (value) {
  21773. this._defaultMaterial = value;
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21779. get: function () {
  21780. return this._texturesEnabled;
  21781. },
  21782. set: function (value) {
  21783. if (this._texturesEnabled === value) {
  21784. return;
  21785. }
  21786. this._texturesEnabled = value;
  21787. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21793. get: function () {
  21794. return this._skeletonsEnabled;
  21795. },
  21796. set: function (value) {
  21797. if (this._skeletonsEnabled === value) {
  21798. return;
  21799. }
  21800. this._skeletonsEnabled = value;
  21801. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21807. get: function () {
  21808. if (!this._postProcessRenderPipelineManager) {
  21809. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21810. }
  21811. return this._postProcessRenderPipelineManager;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21817. get: function () {
  21818. if (!this._mainSoundTrack) {
  21819. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21820. }
  21821. return this._mainSoundTrack;
  21822. },
  21823. enumerable: true,
  21824. configurable: true
  21825. });
  21826. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21827. get: function () {
  21828. return this._alternateRendering;
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21834. get: function () {
  21835. return this._frustumPlanes;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21841. /**
  21842. * Gets the current geometry buffer associated to the scene.
  21843. */
  21844. get: function () {
  21845. return this._geometryBufferRenderer;
  21846. },
  21847. /**
  21848. * Sets the current geometry buffer for the scene.
  21849. */
  21850. set: function (geometryBufferRenderer) {
  21851. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21852. this._geometryBufferRenderer = geometryBufferRenderer;
  21853. }
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Scene.prototype, "debugLayer", {
  21859. // Properties
  21860. get: function () {
  21861. if (!this._debugLayer) {
  21862. this._debugLayer = new BABYLON.DebugLayer(this);
  21863. }
  21864. return this._debugLayer;
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21870. get: function () {
  21871. return this._workerCollisions;
  21872. },
  21873. set: function (enabled) {
  21874. if (!BABYLON.CollisionCoordinatorLegacy) {
  21875. return;
  21876. }
  21877. enabled = (enabled && !!Worker);
  21878. this._workerCollisions = enabled;
  21879. if (this.collisionCoordinator) {
  21880. this.collisionCoordinator.destroy();
  21881. }
  21882. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21883. this.collisionCoordinator.init(this);
  21884. },
  21885. enumerable: true,
  21886. configurable: true
  21887. });
  21888. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21889. get: function () {
  21890. return this._selectionOctree;
  21891. },
  21892. enumerable: true,
  21893. configurable: true
  21894. });
  21895. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21896. /**
  21897. * The mesh that is currently under the pointer.
  21898. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21899. */
  21900. get: function () {
  21901. return this._pointerOverMesh;
  21902. },
  21903. enumerable: true,
  21904. configurable: true
  21905. });
  21906. Object.defineProperty(Scene.prototype, "pointerX", {
  21907. /**
  21908. * Current on-screen X position of the pointer
  21909. * @return {number} X position of the pointer
  21910. */
  21911. get: function () {
  21912. return this._pointerX;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(Scene.prototype, "pointerY", {
  21918. /**
  21919. * Current on-screen Y position of the pointer
  21920. * @return {number} Y position of the pointer
  21921. */
  21922. get: function () {
  21923. return this._pointerY;
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Scene.prototype.getCachedMaterial = function () {
  21929. return this._cachedMaterial;
  21930. };
  21931. Scene.prototype.getCachedEffect = function () {
  21932. return this._cachedEffect;
  21933. };
  21934. Scene.prototype.getCachedVisibility = function () {
  21935. return this._cachedVisibility;
  21936. };
  21937. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21938. if (visibility === void 0) { visibility = 1; }
  21939. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21940. };
  21941. Scene.prototype.getBoundingBoxRenderer = function () {
  21942. if (!this._boundingBoxRenderer) {
  21943. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21944. }
  21945. return this._boundingBoxRenderer;
  21946. };
  21947. Scene.prototype.getOutlineRenderer = function () {
  21948. return this._outlineRenderer;
  21949. };
  21950. Scene.prototype.getEngine = function () {
  21951. return this._engine;
  21952. };
  21953. Scene.prototype.getTotalVertices = function () {
  21954. return this._totalVertices.current;
  21955. };
  21956. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21957. get: function () {
  21958. return this._totalVertices;
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Scene.prototype.getActiveIndices = function () {
  21964. return this._activeIndices.current;
  21965. };
  21966. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21967. get: function () {
  21968. return this._activeIndices;
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. Scene.prototype.getActiveParticles = function () {
  21974. return this._activeParticles.current;
  21975. };
  21976. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21977. get: function () {
  21978. return this._activeParticles;
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Scene.prototype.getActiveBones = function () {
  21984. return this._activeBones.current;
  21985. };
  21986. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21987. get: function () {
  21988. return this._activeBones;
  21989. },
  21990. enumerable: true,
  21991. configurable: true
  21992. });
  21993. // Stats
  21994. Scene.prototype.getInterFramePerfCounter = function () {
  21995. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21996. return 0;
  21997. };
  21998. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21999. get: function () {
  22000. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22001. return null;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Scene.prototype.getLastFrameDuration = function () {
  22007. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22008. return 0;
  22009. };
  22010. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22011. get: function () {
  22012. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22013. return null;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22019. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22020. return 0;
  22021. };
  22022. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22023. get: function () {
  22024. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22025. return null;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Scene.prototype.getActiveMeshes = function () {
  22031. return this._activeMeshes;
  22032. };
  22033. Scene.prototype.getRenderTargetsDuration = function () {
  22034. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22035. return 0;
  22036. };
  22037. Scene.prototype.getRenderDuration = function () {
  22038. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22039. return 0;
  22040. };
  22041. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22042. get: function () {
  22043. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22044. return null;
  22045. },
  22046. enumerable: true,
  22047. configurable: true
  22048. });
  22049. Scene.prototype.getParticlesDuration = function () {
  22050. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22051. return 0;
  22052. };
  22053. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22054. get: function () {
  22055. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22056. return null;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Scene.prototype.getSpritesDuration = function () {
  22062. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22063. return 0;
  22064. };
  22065. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22066. get: function () {
  22067. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22068. return null;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Scene.prototype.getAnimationRatio = function () {
  22074. return this._animationRatio;
  22075. };
  22076. Scene.prototype.getRenderId = function () {
  22077. return this._renderId;
  22078. };
  22079. Scene.prototype.incrementRenderId = function () {
  22080. this._renderId++;
  22081. };
  22082. Scene.prototype._updatePointerPosition = function (evt) {
  22083. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22084. if (!canvasRect) {
  22085. return;
  22086. }
  22087. this._pointerX = evt.clientX - canvasRect.left;
  22088. this._pointerY = evt.clientY - canvasRect.top;
  22089. this._unTranslatedPointerX = this._pointerX;
  22090. this._unTranslatedPointerY = this._pointerY;
  22091. };
  22092. Scene.prototype._createUbo = function () {
  22093. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22094. this._sceneUbo.addUniform("viewProjection", 16);
  22095. this._sceneUbo.addUniform("view", 16);
  22096. };
  22097. Scene.prototype._createAlternateUbo = function () {
  22098. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22099. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22100. this._alternateSceneUbo.addUniform("view", 16);
  22101. };
  22102. // Pointers handling
  22103. /**
  22104. * Use this method to simulate a pointer move on a mesh
  22105. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22106. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22107. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22108. */
  22109. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22110. var evt = new PointerEvent("pointermove", pointerEventInit);
  22111. return this._processPointerMove(pickResult, evt);
  22112. };
  22113. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22114. var canvas = this._engine.getRenderingCanvas();
  22115. if (!canvas) {
  22116. return this;
  22117. }
  22118. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22119. this.setPointerOverSprite(null);
  22120. this.setPointerOverMesh(pickResult.pickedMesh);
  22121. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22122. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22123. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22124. }
  22125. else {
  22126. canvas.style.cursor = this.hoverCursor;
  22127. }
  22128. }
  22129. else {
  22130. canvas.style.cursor = this.defaultCursor;
  22131. }
  22132. }
  22133. else {
  22134. this.setPointerOverMesh(null);
  22135. // Sprites
  22136. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22137. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22138. this.setPointerOverSprite(pickResult.pickedSprite);
  22139. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22140. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22141. }
  22142. else {
  22143. canvas.style.cursor = this.hoverCursor;
  22144. }
  22145. }
  22146. else {
  22147. this.setPointerOverSprite(null);
  22148. // Restore pointer
  22149. canvas.style.cursor = this.defaultCursor;
  22150. }
  22151. }
  22152. if (pickResult) {
  22153. if (this.onPointerMove) {
  22154. this.onPointerMove(evt, pickResult);
  22155. }
  22156. if (this.onPointerObservable.hasObservers()) {
  22157. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22158. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22159. this.onPointerObservable.notifyObservers(pi, type);
  22160. }
  22161. }
  22162. return this;
  22163. };
  22164. /**
  22165. * Use this method to simulate a pointer down on a mesh
  22166. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22167. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22168. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22169. */
  22170. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22171. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22172. return this._processPointerDown(pickResult, evt);
  22173. };
  22174. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22175. var _this = this;
  22176. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22177. this._pickedDownMesh = pickResult.pickedMesh;
  22178. var actionManager = pickResult.pickedMesh.actionManager;
  22179. if (actionManager) {
  22180. if (actionManager.hasPickTriggers) {
  22181. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22182. switch (evt.button) {
  22183. case 0:
  22184. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22185. break;
  22186. case 1:
  22187. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22188. break;
  22189. case 2:
  22190. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22191. break;
  22192. }
  22193. }
  22194. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22195. window.setTimeout(function () {
  22196. 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);
  22197. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22198. if (_this._totalPointersPressed !== 0 &&
  22199. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22200. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22201. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22202. _this._startingPointerTime = 0;
  22203. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22204. }
  22205. }
  22206. }, Scene.LongPressDelay);
  22207. }
  22208. }
  22209. }
  22210. if (pickResult) {
  22211. if (this.onPointerDown) {
  22212. this.onPointerDown(evt, pickResult);
  22213. }
  22214. if (this.onPointerObservable.hasObservers()) {
  22215. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22216. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22217. this.onPointerObservable.notifyObservers(pi, type);
  22218. }
  22219. }
  22220. return this;
  22221. };
  22222. /**
  22223. * Use this method to simulate a pointer up on a mesh
  22224. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22225. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22226. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22227. */
  22228. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22229. var evt = new PointerEvent("pointerup", pointerEventInit);
  22230. var clickInfo = new ClickInfo();
  22231. clickInfo.singleClick = true;
  22232. clickInfo.ignore = true;
  22233. return this._processPointerUp(pickResult, evt, clickInfo);
  22234. };
  22235. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22236. if (pickResult && pickResult && pickResult.pickedMesh) {
  22237. this._pickedUpMesh = pickResult.pickedMesh;
  22238. if (this._pickedDownMesh === this._pickedUpMesh) {
  22239. if (this.onPointerPick) {
  22240. this.onPointerPick(evt, pickResult);
  22241. }
  22242. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22243. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22244. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22245. this.onPointerObservable.notifyObservers(pi, type);
  22246. }
  22247. }
  22248. if (pickResult.pickedMesh.actionManager) {
  22249. if (clickInfo.ignore) {
  22250. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22251. }
  22252. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22253. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22254. }
  22255. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22256. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22257. }
  22258. }
  22259. }
  22260. if (this._pickedDownMesh &&
  22261. this._pickedDownMesh.actionManager &&
  22262. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22263. this._pickedDownMesh !== this._pickedUpMesh) {
  22264. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22265. }
  22266. if (this.onPointerUp) {
  22267. this.onPointerUp(evt, pickResult);
  22268. }
  22269. if (this.onPointerObservable.hasObservers()) {
  22270. if (!clickInfo.ignore) {
  22271. if (!clickInfo.hasSwiped) {
  22272. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22273. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22274. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22275. this.onPointerObservable.notifyObservers(pi, type);
  22276. }
  22277. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22278. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22279. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22280. this.onPointerObservable.notifyObservers(pi, type);
  22281. }
  22282. }
  22283. }
  22284. else {
  22285. var type = BABYLON.PointerEventTypes.POINTERUP;
  22286. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22287. this.onPointerObservable.notifyObservers(pi, type);
  22288. }
  22289. }
  22290. return this;
  22291. };
  22292. /**
  22293. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22294. * @param attachUp defines if you want to attach events to pointerup
  22295. * @param attachDown defines if you want to attach events to pointerdown
  22296. * @param attachMove defines if you want to attach events to pointermove
  22297. */
  22298. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22299. var _this = this;
  22300. if (attachUp === void 0) { attachUp = true; }
  22301. if (attachDown === void 0) { attachDown = true; }
  22302. if (attachMove === void 0) { attachMove = true; }
  22303. this._initActionManager = function (act, clickInfo) {
  22304. if (!_this._meshPickProceed) {
  22305. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22306. _this._currentPickResult = pickResult;
  22307. if (pickResult) {
  22308. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22309. }
  22310. _this._meshPickProceed = true;
  22311. }
  22312. return act;
  22313. };
  22314. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22315. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22316. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22317. btn !== _this._previousButtonPressed) {
  22318. _this._doubleClickOccured = false;
  22319. clickInfo.singleClick = true;
  22320. clickInfo.ignore = false;
  22321. cb(clickInfo, _this._currentPickResult);
  22322. }
  22323. };
  22324. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22325. var clickInfo = new ClickInfo();
  22326. _this._currentPickResult = null;
  22327. var act = null;
  22328. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22329. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22330. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22331. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22332. act = _this._initActionManager(act, clickInfo);
  22333. if (act)
  22334. checkPicking = act.hasPickTriggers;
  22335. }
  22336. if (checkPicking) {
  22337. var btn = evt.button;
  22338. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22339. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22340. if (!clickInfo.hasSwiped) {
  22341. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22342. if (!checkSingleClickImmediately) {
  22343. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22344. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22345. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22346. act = _this._initActionManager(act, clickInfo);
  22347. if (act)
  22348. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22349. }
  22350. }
  22351. if (checkSingleClickImmediately) {
  22352. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22353. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22354. btn !== _this._previousButtonPressed) {
  22355. clickInfo.singleClick = true;
  22356. cb(clickInfo, _this._currentPickResult);
  22357. }
  22358. }
  22359. else {
  22360. // wait that no double click has been raised during the double click delay
  22361. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22362. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22363. }
  22364. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22365. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22366. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22367. act = _this._initActionManager(act, clickInfo);
  22368. if (act)
  22369. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22370. }
  22371. if (checkDoubleClick) {
  22372. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22373. if (btn === _this._previousButtonPressed &&
  22374. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22375. !_this._doubleClickOccured) {
  22376. // pointer has not moved for 2 clicks, it's a double click
  22377. if (!clickInfo.hasSwiped &&
  22378. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22379. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22380. _this._previousStartingPointerTime = 0;
  22381. _this._doubleClickOccured = true;
  22382. clickInfo.doubleClick = true;
  22383. clickInfo.ignore = false;
  22384. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22385. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22386. }
  22387. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22388. cb(clickInfo, _this._currentPickResult);
  22389. }
  22390. else {
  22391. _this._doubleClickOccured = false;
  22392. _this._previousStartingPointerTime = _this._startingPointerTime;
  22393. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22394. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22395. _this._previousButtonPressed = btn;
  22396. if (Scene.ExclusiveDoubleClickMode) {
  22397. if (_this._previousDelayedSimpleClickTimeout) {
  22398. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22399. }
  22400. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22401. cb(clickInfo, _this._previousPickResult);
  22402. }
  22403. else {
  22404. cb(clickInfo, _this._currentPickResult);
  22405. }
  22406. }
  22407. }
  22408. else {
  22409. _this._doubleClickOccured = false;
  22410. _this._previousStartingPointerTime = _this._startingPointerTime;
  22411. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22412. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22413. _this._previousButtonPressed = btn;
  22414. }
  22415. }
  22416. }
  22417. }
  22418. clickInfo.ignore = true;
  22419. cb(clickInfo, _this._currentPickResult);
  22420. };
  22421. this._spritePredicate = function (sprite) {
  22422. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22423. };
  22424. this._onPointerMove = function (evt) {
  22425. _this._updatePointerPosition(evt);
  22426. // PreObservable support
  22427. if (_this.onPrePointerObservable.hasObservers()) {
  22428. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22429. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22430. _this.onPrePointerObservable.notifyObservers(pi, type);
  22431. if (pi.skipOnPointerObservable) {
  22432. return;
  22433. }
  22434. }
  22435. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22436. return;
  22437. }
  22438. if (!_this.pointerMovePredicate) {
  22439. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22440. }
  22441. // Meshes
  22442. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22443. _this._processPointerMove(pickResult, evt);
  22444. };
  22445. this._onPointerDown = function (evt) {
  22446. _this._totalPointersPressed++;
  22447. _this._pickedDownMesh = null;
  22448. _this._meshPickProceed = false;
  22449. _this._updatePointerPosition(evt);
  22450. if (_this.preventDefaultOnPointerDown && canvas) {
  22451. evt.preventDefault();
  22452. canvas.focus();
  22453. }
  22454. // PreObservable support
  22455. if (_this.onPrePointerObservable.hasObservers()) {
  22456. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22457. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22458. _this.onPrePointerObservable.notifyObservers(pi, type);
  22459. if (pi.skipOnPointerObservable) {
  22460. return;
  22461. }
  22462. }
  22463. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22464. return;
  22465. }
  22466. _this._startingPointerPosition.x = _this._pointerX;
  22467. _this._startingPointerPosition.y = _this._pointerY;
  22468. _this._startingPointerTime = new Date().getTime();
  22469. if (!_this.pointerDownPredicate) {
  22470. _this.pointerDownPredicate = function (mesh) {
  22471. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22472. };
  22473. }
  22474. // Meshes
  22475. _this._pickedDownMesh = null;
  22476. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22477. _this._processPointerDown(pickResult, evt);
  22478. // Sprites
  22479. _this._pickedDownSprite = null;
  22480. if (_this.spriteManagers.length > 0) {
  22481. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22482. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22483. if (pickResult.pickedSprite.actionManager) {
  22484. _this._pickedDownSprite = pickResult.pickedSprite;
  22485. switch (evt.button) {
  22486. case 0:
  22487. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22488. break;
  22489. case 1:
  22490. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22491. break;
  22492. case 2:
  22493. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22494. break;
  22495. }
  22496. if (pickResult.pickedSprite.actionManager) {
  22497. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22498. }
  22499. }
  22500. }
  22501. }
  22502. };
  22503. this._onPointerUp = function (evt) {
  22504. if (_this._totalPointersPressed === 0) {
  22505. return; // So we need to test it the pointer down was pressed before.
  22506. }
  22507. _this._totalPointersPressed--;
  22508. _this._pickedUpMesh = null;
  22509. _this._meshPickProceed = false;
  22510. _this._updatePointerPosition(evt);
  22511. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22512. // PreObservable support
  22513. if (_this.onPrePointerObservable.hasObservers()) {
  22514. if (!clickInfo.ignore) {
  22515. if (!clickInfo.hasSwiped) {
  22516. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22517. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22518. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22519. _this.onPrePointerObservable.notifyObservers(pi, type);
  22520. if (pi.skipOnPointerObservable) {
  22521. return;
  22522. }
  22523. }
  22524. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22525. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22526. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22527. _this.onPrePointerObservable.notifyObservers(pi, type);
  22528. if (pi.skipOnPointerObservable) {
  22529. return;
  22530. }
  22531. }
  22532. }
  22533. }
  22534. else {
  22535. var type = BABYLON.PointerEventTypes.POINTERUP;
  22536. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22537. _this.onPrePointerObservable.notifyObservers(pi, type);
  22538. if (pi.skipOnPointerObservable) {
  22539. return;
  22540. }
  22541. }
  22542. }
  22543. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22544. return;
  22545. }
  22546. if (!_this.pointerUpPredicate) {
  22547. _this.pointerUpPredicate = function (mesh) {
  22548. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22549. };
  22550. }
  22551. // Meshes
  22552. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22553. _this._initActionManager(null, clickInfo);
  22554. }
  22555. if (!pickResult) {
  22556. pickResult = _this._currentPickResult;
  22557. }
  22558. _this._processPointerUp(pickResult, evt, clickInfo);
  22559. // Sprites
  22560. if (_this.spriteManagers.length > 0) {
  22561. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22562. if (spritePickResult) {
  22563. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22564. if (spritePickResult.pickedSprite.actionManager) {
  22565. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22566. if (spritePickResult.pickedSprite.actionManager) {
  22567. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22568. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22569. }
  22570. }
  22571. }
  22572. }
  22573. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22574. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22575. }
  22576. }
  22577. }
  22578. _this._previousPickResult = _this._currentPickResult;
  22579. });
  22580. };
  22581. this._onKeyDown = function (evt) {
  22582. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22583. if (_this.onPreKeyboardObservable.hasObservers()) {
  22584. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22585. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22586. if (pi.skipOnPointerObservable) {
  22587. return;
  22588. }
  22589. }
  22590. if (_this.onKeyboardObservable.hasObservers()) {
  22591. var pi = new BABYLON.KeyboardInfo(type, evt);
  22592. _this.onKeyboardObservable.notifyObservers(pi, type);
  22593. }
  22594. if (_this.actionManager) {
  22595. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22596. }
  22597. };
  22598. this._onKeyUp = function (evt) {
  22599. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22600. if (_this.onPreKeyboardObservable.hasObservers()) {
  22601. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22602. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22603. if (pi.skipOnPointerObservable) {
  22604. return;
  22605. }
  22606. }
  22607. if (_this.onKeyboardObservable.hasObservers()) {
  22608. var pi = new BABYLON.KeyboardInfo(type, evt);
  22609. _this.onKeyboardObservable.notifyObservers(pi, type);
  22610. }
  22611. if (_this.actionManager) {
  22612. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22613. }
  22614. };
  22615. var engine = this.getEngine();
  22616. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22617. if (!canvas) {
  22618. return;
  22619. }
  22620. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22621. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22622. });
  22623. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22624. if (!canvas) {
  22625. return;
  22626. }
  22627. canvas.removeEventListener("keydown", _this._onKeyDown);
  22628. canvas.removeEventListener("keyup", _this._onKeyUp);
  22629. });
  22630. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22631. var canvas = this._engine.getRenderingCanvas();
  22632. if (!canvas) {
  22633. return;
  22634. }
  22635. if (attachMove) {
  22636. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22637. // Wheel
  22638. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22639. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22640. }
  22641. if (attachDown) {
  22642. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22643. }
  22644. if (attachUp) {
  22645. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22646. }
  22647. canvas.tabIndex = 1;
  22648. };
  22649. Scene.prototype.detachControl = function () {
  22650. var engine = this.getEngine();
  22651. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22652. var canvas = engine.getRenderingCanvas();
  22653. if (!canvas) {
  22654. return;
  22655. }
  22656. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22657. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22658. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22659. if (this._onCanvasBlurObserver) {
  22660. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22661. }
  22662. if (this._onCanvasFocusObserver) {
  22663. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22664. }
  22665. // Wheel
  22666. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22667. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22668. // Keyboard
  22669. canvas.removeEventListener("keydown", this._onKeyDown);
  22670. canvas.removeEventListener("keyup", this._onKeyUp);
  22671. // Observables
  22672. this.onKeyboardObservable.clear();
  22673. this.onPreKeyboardObservable.clear();
  22674. this.onPointerObservable.clear();
  22675. this.onPrePointerObservable.clear();
  22676. };
  22677. /**
  22678. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22679. * Delay loaded resources are not taking in account
  22680. * @return true if all required resources are ready
  22681. */
  22682. Scene.prototype.isReady = function () {
  22683. if (this._isDisposed) {
  22684. return false;
  22685. }
  22686. if (this._pendingData.length > 0) {
  22687. return false;
  22688. }
  22689. var index;
  22690. var engine = this.getEngine();
  22691. // Geometries
  22692. for (index = 0; index < this._geometries.length; index++) {
  22693. var geometry = this._geometries[index];
  22694. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22695. return false;
  22696. }
  22697. }
  22698. // Meshes
  22699. for (index = 0; index < this.meshes.length; index++) {
  22700. var mesh = this.meshes[index];
  22701. if (!mesh.isEnabled()) {
  22702. continue;
  22703. }
  22704. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22705. continue;
  22706. }
  22707. if (!mesh.isReady(true)) {
  22708. return false;
  22709. }
  22710. // Effect layers
  22711. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22712. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22713. var layer = _a[_i];
  22714. if (!layer.hasMesh(mesh)) {
  22715. continue;
  22716. }
  22717. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22718. var subMesh = _c[_b];
  22719. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22720. return false;
  22721. }
  22722. }
  22723. }
  22724. }
  22725. return true;
  22726. };
  22727. Scene.prototype.resetCachedMaterial = function () {
  22728. this._cachedMaterial = null;
  22729. this._cachedEffect = null;
  22730. this._cachedVisibility = null;
  22731. };
  22732. Scene.prototype.registerBeforeRender = function (func) {
  22733. this.onBeforeRenderObservable.add(func);
  22734. };
  22735. Scene.prototype.unregisterBeforeRender = function (func) {
  22736. this.onBeforeRenderObservable.removeCallback(func);
  22737. };
  22738. Scene.prototype.registerAfterRender = function (func) {
  22739. this.onAfterRenderObservable.add(func);
  22740. };
  22741. Scene.prototype.unregisterAfterRender = function (func) {
  22742. this.onAfterRenderObservable.removeCallback(func);
  22743. };
  22744. Scene.prototype._executeOnceBeforeRender = function (func) {
  22745. var _this = this;
  22746. var execFunc = function () {
  22747. func();
  22748. setTimeout(function () {
  22749. _this.unregisterBeforeRender(execFunc);
  22750. });
  22751. };
  22752. this.registerBeforeRender(execFunc);
  22753. };
  22754. /**
  22755. * The provided function will run before render once and will be disposed afterwards.
  22756. * A timeout delay can be provided so that the function will be executed in N ms.
  22757. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22758. * @param func The function to be executed.
  22759. * @param timeout optional delay in ms
  22760. */
  22761. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22762. var _this = this;
  22763. if (timeout !== undefined) {
  22764. setTimeout(function () {
  22765. _this._executeOnceBeforeRender(func);
  22766. }, timeout);
  22767. }
  22768. else {
  22769. this._executeOnceBeforeRender(func);
  22770. }
  22771. };
  22772. Scene.prototype._addPendingData = function (data) {
  22773. this._pendingData.push(data);
  22774. };
  22775. Scene.prototype._removePendingData = function (data) {
  22776. var wasLoading = this.isLoading;
  22777. var index = this._pendingData.indexOf(data);
  22778. if (index !== -1) {
  22779. this._pendingData.splice(index, 1);
  22780. }
  22781. if (wasLoading && !this.isLoading) {
  22782. this.onDataLoadedObservable.notifyObservers(this);
  22783. }
  22784. };
  22785. Scene.prototype.getWaitingItemsCount = function () {
  22786. return this._pendingData.length;
  22787. };
  22788. Object.defineProperty(Scene.prototype, "isLoading", {
  22789. get: function () {
  22790. return this._pendingData.length > 0;
  22791. },
  22792. enumerable: true,
  22793. configurable: true
  22794. });
  22795. /**
  22796. * Registers a function to be executed when the scene is ready.
  22797. * @param {Function} func - the function to be executed.
  22798. */
  22799. Scene.prototype.executeWhenReady = function (func) {
  22800. var _this = this;
  22801. this.onReadyObservable.add(func);
  22802. if (this._executeWhenReadyTimeoutId !== -1) {
  22803. return;
  22804. }
  22805. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22806. _this._checkIsReady();
  22807. }, 150);
  22808. };
  22809. /**
  22810. * Returns a promise that resolves when the scene is ready.
  22811. * @returns A promise that resolves when the scene is ready.
  22812. */
  22813. Scene.prototype.whenReadyAsync = function () {
  22814. var _this = this;
  22815. return new Promise(function (resolve) {
  22816. _this.executeWhenReady(function () {
  22817. resolve();
  22818. });
  22819. });
  22820. };
  22821. Scene.prototype._checkIsReady = function () {
  22822. var _this = this;
  22823. if (this.isReady()) {
  22824. this.onReadyObservable.notifyObservers(this);
  22825. this.onReadyObservable.clear();
  22826. this._executeWhenReadyTimeoutId = -1;
  22827. return;
  22828. }
  22829. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22830. _this._checkIsReady();
  22831. }, 150);
  22832. };
  22833. // Animations
  22834. /**
  22835. * Will start the animation sequence of a given target
  22836. * @param target - the target
  22837. * @param {number} from - from which frame should animation start
  22838. * @param {number} to - till which frame should animation run.
  22839. * @param {boolean} [loop] - should the animation loop
  22840. * @param {number} [speedRatio] - the speed in which to run the animation
  22841. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22842. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22843. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22844. * See BABYLON.Animatable
  22845. */
  22846. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22847. if (speedRatio === void 0) { speedRatio = 1.0; }
  22848. if (from > to && speedRatio > 0) {
  22849. speedRatio *= -1;
  22850. }
  22851. this.stopAnimation(target);
  22852. if (!animatable) {
  22853. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22854. }
  22855. // Local animations
  22856. if (target.animations) {
  22857. animatable.appendAnimations(target, target.animations);
  22858. }
  22859. // Children animations
  22860. if (target.getAnimatables) {
  22861. var animatables = target.getAnimatables();
  22862. for (var index = 0; index < animatables.length; index++) {
  22863. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22864. }
  22865. }
  22866. animatable.reset();
  22867. return animatable;
  22868. };
  22869. /**
  22870. * Begin a new animation on a given node
  22871. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22872. * @param {BABYLON.Animation[]} defines the list of animations to start
  22873. * @param {number} from defines the initial value
  22874. * @param {number} to defines the final value
  22875. * @param {boolean} loop defines if you want animation to loop (off by default)
  22876. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22877. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22878. * @returns the list of created animatables
  22879. */
  22880. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22881. if (speedRatio === undefined) {
  22882. speedRatio = 1.0;
  22883. }
  22884. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22885. return animatable;
  22886. };
  22887. /**
  22888. * Begin a new animation on a given node and its hierarchy
  22889. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22890. * @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.
  22891. * @param {BABYLON.Animation[]} defines the list of animations to start
  22892. * @param {number} from defines the initial value
  22893. * @param {number} to defines the final value
  22894. * @param {boolean} loop defines if you want animation to loop (off by default)
  22895. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22896. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22897. * @returns the list of animatables created for all nodes
  22898. */
  22899. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22900. var children = target.getDescendants(directDescendantsOnly);
  22901. var result = [];
  22902. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22903. var child = children_1[_i];
  22904. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22905. }
  22906. return result;
  22907. };
  22908. Scene.prototype.getAnimatableByTarget = function (target) {
  22909. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22910. if (this._activeAnimatables[index].target === target) {
  22911. return this._activeAnimatables[index];
  22912. }
  22913. }
  22914. return null;
  22915. };
  22916. Object.defineProperty(Scene.prototype, "animatables", {
  22917. get: function () {
  22918. return this._activeAnimatables;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. /**
  22924. * Will stop the animation of the given target
  22925. * @param target - the target
  22926. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22927. * @see beginAnimation
  22928. */
  22929. Scene.prototype.stopAnimation = function (target, animationName) {
  22930. var animatable = this.getAnimatableByTarget(target);
  22931. if (animatable) {
  22932. animatable.stop(animationName);
  22933. }
  22934. };
  22935. /**
  22936. * Stops and removes all animations that have been applied to the scene
  22937. */
  22938. Scene.prototype.stopAllAnimations = function () {
  22939. if (this._activeAnimatables) {
  22940. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22941. this._activeAnimatables[i].stop();
  22942. }
  22943. this._activeAnimatables = [];
  22944. }
  22945. };
  22946. Scene.prototype._animate = function () {
  22947. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22948. return;
  22949. }
  22950. // Getting time
  22951. var now = BABYLON.Tools.Now;
  22952. if (!this._animationTimeLast) {
  22953. if (this._pendingData.length > 0) {
  22954. return;
  22955. }
  22956. this._animationTimeLast = now;
  22957. }
  22958. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22959. this._animationTime += deltaTime;
  22960. this._animationTimeLast = now;
  22961. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22962. this._activeAnimatables[index]._animate(this._animationTime);
  22963. }
  22964. };
  22965. // Matrix
  22966. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22967. this._useAlternateCameraConfiguration = active;
  22968. };
  22969. Scene.prototype.getViewMatrix = function () {
  22970. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22971. };
  22972. Scene.prototype.getProjectionMatrix = function () {
  22973. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22974. };
  22975. Scene.prototype.getTransformMatrix = function () {
  22976. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22977. };
  22978. Scene.prototype.setTransformMatrix = function (view, projection) {
  22979. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22980. return;
  22981. }
  22982. this._viewUpdateFlag = view.updateFlag;
  22983. this._projectionUpdateFlag = projection.updateFlag;
  22984. this._viewMatrix = view;
  22985. this._projectionMatrix = projection;
  22986. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22987. // Update frustum
  22988. if (!this._frustumPlanes) {
  22989. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22990. }
  22991. else {
  22992. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22993. }
  22994. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22995. var otherCamera = this.activeCamera._alternateCamera;
  22996. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22997. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22998. }
  22999. if (this._sceneUbo.useUbo) {
  23000. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23001. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23002. this._sceneUbo.update();
  23003. }
  23004. };
  23005. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23006. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23007. return;
  23008. }
  23009. this._alternateViewUpdateFlag = view.updateFlag;
  23010. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23011. this._alternateViewMatrix = view;
  23012. this._alternateProjectionMatrix = projection;
  23013. if (!this._alternateTransformMatrix) {
  23014. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23015. }
  23016. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23017. if (!this._alternateSceneUbo) {
  23018. this._createAlternateUbo();
  23019. }
  23020. if (this._alternateSceneUbo.useUbo) {
  23021. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23022. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23023. this._alternateSceneUbo.update();
  23024. }
  23025. };
  23026. Scene.prototype.getSceneUniformBuffer = function () {
  23027. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23028. };
  23029. // Methods
  23030. Scene.prototype.getUniqueId = function () {
  23031. var result = Scene._uniqueIdCounter;
  23032. Scene._uniqueIdCounter++;
  23033. return result;
  23034. };
  23035. Scene.prototype.addMesh = function (newMesh) {
  23036. this.meshes.push(newMesh);
  23037. //notify the collision coordinator
  23038. if (this.collisionCoordinator) {
  23039. this.collisionCoordinator.onMeshAdded(newMesh);
  23040. }
  23041. newMesh._resyncLightSources();
  23042. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23043. };
  23044. Scene.prototype.removeMesh = function (toRemove) {
  23045. var index = this.meshes.indexOf(toRemove);
  23046. if (index !== -1) {
  23047. // Remove from the scene if mesh found
  23048. this.meshes.splice(index, 1);
  23049. }
  23050. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23051. return index;
  23052. };
  23053. Scene.prototype.addTransformNode = function (newTransformNode) {
  23054. this.transformNodes.push(newTransformNode);
  23055. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23056. };
  23057. Scene.prototype.removeTransformNode = function (toRemove) {
  23058. var index = this.transformNodes.indexOf(toRemove);
  23059. if (index !== -1) {
  23060. // Remove from the scene if found
  23061. this.transformNodes.splice(index, 1);
  23062. }
  23063. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23064. return index;
  23065. };
  23066. Scene.prototype.removeSkeleton = function (toRemove) {
  23067. var index = this.skeletons.indexOf(toRemove);
  23068. if (index !== -1) {
  23069. // Remove from the scene if found
  23070. this.skeletons.splice(index, 1);
  23071. }
  23072. return index;
  23073. };
  23074. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23075. var index = this.morphTargetManagers.indexOf(toRemove);
  23076. if (index !== -1) {
  23077. // Remove from the scene if found
  23078. this.morphTargetManagers.splice(index, 1);
  23079. }
  23080. return index;
  23081. };
  23082. Scene.prototype.removeLight = function (toRemove) {
  23083. var index = this.lights.indexOf(toRemove);
  23084. if (index !== -1) {
  23085. // Remove from meshes
  23086. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23087. var mesh = _a[_i];
  23088. mesh._removeLightSource(toRemove);
  23089. }
  23090. // Remove from the scene if mesh found
  23091. this.lights.splice(index, 1);
  23092. this.sortLightsByPriority();
  23093. }
  23094. this.onLightRemovedObservable.notifyObservers(toRemove);
  23095. return index;
  23096. };
  23097. Scene.prototype.removeCamera = function (toRemove) {
  23098. var index = this.cameras.indexOf(toRemove);
  23099. if (index !== -1) {
  23100. // Remove from the scene if mesh found
  23101. this.cameras.splice(index, 1);
  23102. }
  23103. // Remove from activeCameras
  23104. var index2 = this.activeCameras.indexOf(toRemove);
  23105. if (index2 !== -1) {
  23106. // Remove from the scene if mesh found
  23107. this.activeCameras.splice(index2, 1);
  23108. }
  23109. // Reset the activeCamera
  23110. if (this.activeCamera === toRemove) {
  23111. if (this.cameras.length > 0) {
  23112. this.activeCamera = this.cameras[0];
  23113. }
  23114. else {
  23115. this.activeCamera = null;
  23116. }
  23117. }
  23118. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23119. return index;
  23120. };
  23121. Scene.prototype.removeParticleSystem = function (toRemove) {
  23122. var index = this.particleSystems.indexOf(toRemove);
  23123. if (index !== -1) {
  23124. this.particleSystems.splice(index, 1);
  23125. }
  23126. return index;
  23127. };
  23128. ;
  23129. Scene.prototype.removeAnimation = function (toRemove) {
  23130. var index = this.animations.indexOf(toRemove);
  23131. if (index !== -1) {
  23132. this.animations.splice(index, 1);
  23133. }
  23134. return index;
  23135. };
  23136. ;
  23137. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23138. var index = this.multiMaterials.indexOf(toRemove);
  23139. if (index !== -1) {
  23140. this.multiMaterials.splice(index, 1);
  23141. }
  23142. return index;
  23143. };
  23144. ;
  23145. Scene.prototype.removeMaterial = function (toRemove) {
  23146. var index = this.materials.indexOf(toRemove);
  23147. if (index !== -1) {
  23148. this.materials.splice(index, 1);
  23149. }
  23150. return index;
  23151. };
  23152. ;
  23153. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23154. var index = this.lensFlareSystems.indexOf(toRemove);
  23155. if (index !== -1) {
  23156. this.lensFlareSystems.splice(index, 1);
  23157. }
  23158. return index;
  23159. };
  23160. ;
  23161. Scene.prototype.removeActionManager = function (toRemove) {
  23162. var index = this._actionManagers.indexOf(toRemove);
  23163. if (index !== -1) {
  23164. this._actionManagers.splice(index, 1);
  23165. }
  23166. return index;
  23167. };
  23168. ;
  23169. Scene.prototype.addLight = function (newLight) {
  23170. this.lights.push(newLight);
  23171. this.sortLightsByPriority();
  23172. // Add light to all meshes (To support if the light is removed and then readded)
  23173. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23174. var mesh = _a[_i];
  23175. if (mesh._lightSources.indexOf(newLight) === -1) {
  23176. mesh._lightSources.push(newLight);
  23177. mesh._resyncLightSources();
  23178. }
  23179. }
  23180. this.onNewLightAddedObservable.notifyObservers(newLight);
  23181. };
  23182. Scene.prototype.sortLightsByPriority = function () {
  23183. if (this.requireLightSorting) {
  23184. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23185. }
  23186. };
  23187. Scene.prototype.addCamera = function (newCamera) {
  23188. this.cameras.push(newCamera);
  23189. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23190. };
  23191. Scene.prototype.addSkeleton = function (newSkeleton) {
  23192. this.skeletons.push(newSkeleton);
  23193. };
  23194. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23195. this.particleSystems.push(newParticleSystem);
  23196. };
  23197. Scene.prototype.addAnimation = function (newAnimation) {
  23198. this.animations.push(newAnimation);
  23199. };
  23200. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23201. this.multiMaterials.push(newMultiMaterial);
  23202. };
  23203. Scene.prototype.addMaterial = function (newMaterial) {
  23204. this.materials.push(newMaterial);
  23205. };
  23206. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23207. this.morphTargetManagers.push(newMorphTargetManager);
  23208. };
  23209. Scene.prototype.addGeometry = function (newGeometrie) {
  23210. this._geometries.push(newGeometrie);
  23211. };
  23212. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23213. this.lensFlareSystems.push(newLensFlareSystem);
  23214. };
  23215. Scene.prototype.addActionManager = function (newActionManager) {
  23216. this._actionManagers.push(newActionManager);
  23217. };
  23218. /**
  23219. * Switch active camera
  23220. * @param {Camera} newCamera - new active camera
  23221. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23222. */
  23223. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23224. if (attachControl === void 0) { attachControl = true; }
  23225. var canvas = this._engine.getRenderingCanvas();
  23226. if (!canvas) {
  23227. return;
  23228. }
  23229. if (this.activeCamera) {
  23230. this.activeCamera.detachControl(canvas);
  23231. }
  23232. this.activeCamera = newCamera;
  23233. if (attachControl) {
  23234. newCamera.attachControl(canvas);
  23235. }
  23236. };
  23237. /**
  23238. * sets the active camera of the scene using its ID
  23239. * @param {string} id - the camera's ID
  23240. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23241. * @see activeCamera
  23242. */
  23243. Scene.prototype.setActiveCameraByID = function (id) {
  23244. var camera = this.getCameraByID(id);
  23245. if (camera) {
  23246. this.activeCamera = camera;
  23247. return camera;
  23248. }
  23249. return null;
  23250. };
  23251. /**
  23252. * sets the active camera of the scene using its name
  23253. * @param {string} name - the camera's name
  23254. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23255. * @see activeCamera
  23256. */
  23257. Scene.prototype.setActiveCameraByName = function (name) {
  23258. var camera = this.getCameraByName(name);
  23259. if (camera) {
  23260. this.activeCamera = camera;
  23261. return camera;
  23262. }
  23263. return null;
  23264. };
  23265. /**
  23266. * get an animation group using its name
  23267. * @param {string} the material's name
  23268. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23269. */
  23270. Scene.prototype.getAnimationGroupByName = function (name) {
  23271. for (var index = 0; index < this.animationGroups.length; index++) {
  23272. if (this.animationGroups[index].name === name) {
  23273. return this.animationGroups[index];
  23274. }
  23275. }
  23276. return null;
  23277. };
  23278. /**
  23279. * get a material using its id
  23280. * @param {string} the material's ID
  23281. * @return {BABYLON.Material|null} the material or null if none found.
  23282. */
  23283. Scene.prototype.getMaterialByID = function (id) {
  23284. for (var index = 0; index < this.materials.length; index++) {
  23285. if (this.materials[index].id === id) {
  23286. return this.materials[index];
  23287. }
  23288. }
  23289. return null;
  23290. };
  23291. /**
  23292. * get a material using its name
  23293. * @param {string} the material's name
  23294. * @return {BABYLON.Material|null} the material or null if none found.
  23295. */
  23296. Scene.prototype.getMaterialByName = function (name) {
  23297. for (var index = 0; index < this.materials.length; index++) {
  23298. if (this.materials[index].name === name) {
  23299. return this.materials[index];
  23300. }
  23301. }
  23302. return null;
  23303. };
  23304. Scene.prototype.getLensFlareSystemByName = function (name) {
  23305. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23306. if (this.lensFlareSystems[index].name === name) {
  23307. return this.lensFlareSystems[index];
  23308. }
  23309. }
  23310. return null;
  23311. };
  23312. Scene.prototype.getLensFlareSystemByID = function (id) {
  23313. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23314. if (this.lensFlareSystems[index].id === id) {
  23315. return this.lensFlareSystems[index];
  23316. }
  23317. }
  23318. return null;
  23319. };
  23320. Scene.prototype.getCameraByID = function (id) {
  23321. for (var index = 0; index < this.cameras.length; index++) {
  23322. if (this.cameras[index].id === id) {
  23323. return this.cameras[index];
  23324. }
  23325. }
  23326. return null;
  23327. };
  23328. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23329. for (var index = 0; index < this.cameras.length; index++) {
  23330. if (this.cameras[index].uniqueId === uniqueId) {
  23331. return this.cameras[index];
  23332. }
  23333. }
  23334. return null;
  23335. };
  23336. /**
  23337. * get a camera using its name
  23338. * @param {string} the camera's name
  23339. * @return {BABYLON.Camera|null} the camera or null if none found.
  23340. */
  23341. Scene.prototype.getCameraByName = function (name) {
  23342. for (var index = 0; index < this.cameras.length; index++) {
  23343. if (this.cameras[index].name === name) {
  23344. return this.cameras[index];
  23345. }
  23346. }
  23347. return null;
  23348. };
  23349. /**
  23350. * get a bone using its id
  23351. * @param {string} the bone's id
  23352. * @return {BABYLON.Bone|null} the bone or null if not found
  23353. */
  23354. Scene.prototype.getBoneByID = function (id) {
  23355. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23356. var skeleton = this.skeletons[skeletonIndex];
  23357. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23358. if (skeleton.bones[boneIndex].id === id) {
  23359. return skeleton.bones[boneIndex];
  23360. }
  23361. }
  23362. }
  23363. return null;
  23364. };
  23365. /**
  23366. * get a bone using its id
  23367. * @param {string} the bone's name
  23368. * @return {BABYLON.Bone|null} the bone or null if not found
  23369. */
  23370. Scene.prototype.getBoneByName = function (name) {
  23371. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23372. var skeleton = this.skeletons[skeletonIndex];
  23373. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23374. if (skeleton.bones[boneIndex].name === name) {
  23375. return skeleton.bones[boneIndex];
  23376. }
  23377. }
  23378. }
  23379. return null;
  23380. };
  23381. /**
  23382. * get a light node using its name
  23383. * @param {string} the light's name
  23384. * @return {BABYLON.Light|null} the light or null if none found.
  23385. */
  23386. Scene.prototype.getLightByName = function (name) {
  23387. for (var index = 0; index < this.lights.length; index++) {
  23388. if (this.lights[index].name === name) {
  23389. return this.lights[index];
  23390. }
  23391. }
  23392. return null;
  23393. };
  23394. /**
  23395. * get a light node using its ID
  23396. * @param {string} the light's id
  23397. * @return {BABYLON.Light|null} the light or null if none found.
  23398. */
  23399. Scene.prototype.getLightByID = function (id) {
  23400. for (var index = 0; index < this.lights.length; index++) {
  23401. if (this.lights[index].id === id) {
  23402. return this.lights[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. /**
  23408. * get a light node using its scene-generated unique ID
  23409. * @param {number} the light's unique id
  23410. * @return {BABYLON.Light|null} the light or null if none found.
  23411. */
  23412. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23413. for (var index = 0; index < this.lights.length; index++) {
  23414. if (this.lights[index].uniqueId === uniqueId) {
  23415. return this.lights[index];
  23416. }
  23417. }
  23418. return null;
  23419. };
  23420. /**
  23421. * get a particle system by id
  23422. * @param id {number} the particle system id
  23423. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23424. */
  23425. Scene.prototype.getParticleSystemByID = function (id) {
  23426. for (var index = 0; index < this.particleSystems.length; index++) {
  23427. if (this.particleSystems[index].id === id) {
  23428. return this.particleSystems[index];
  23429. }
  23430. }
  23431. return null;
  23432. };
  23433. /**
  23434. * get a geometry using its ID
  23435. * @param {string} the geometry's id
  23436. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23437. */
  23438. Scene.prototype.getGeometryByID = function (id) {
  23439. for (var index = 0; index < this._geometries.length; index++) {
  23440. if (this._geometries[index].id === id) {
  23441. return this._geometries[index];
  23442. }
  23443. }
  23444. return null;
  23445. };
  23446. /**
  23447. * add a new geometry to this scene.
  23448. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23449. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23450. * @return {boolean} was the geometry added or not
  23451. */
  23452. Scene.prototype.pushGeometry = function (geometry, force) {
  23453. if (!force && this.getGeometryByID(geometry.id)) {
  23454. return false;
  23455. }
  23456. this._geometries.push(geometry);
  23457. //notify the collision coordinator
  23458. if (this.collisionCoordinator) {
  23459. this.collisionCoordinator.onGeometryAdded(geometry);
  23460. }
  23461. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23462. return true;
  23463. };
  23464. /**
  23465. * Removes an existing geometry
  23466. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23467. * @return {boolean} was the geometry removed or not
  23468. */
  23469. Scene.prototype.removeGeometry = function (geometry) {
  23470. var index = this._geometries.indexOf(geometry);
  23471. if (index > -1) {
  23472. this._geometries.splice(index, 1);
  23473. //notify the collision coordinator
  23474. if (this.collisionCoordinator) {
  23475. this.collisionCoordinator.onGeometryDeleted(geometry);
  23476. }
  23477. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23478. return true;
  23479. }
  23480. return false;
  23481. };
  23482. Scene.prototype.getGeometries = function () {
  23483. return this._geometries;
  23484. };
  23485. /**
  23486. * Get the first added mesh found of a given ID
  23487. * @param {string} id - the id to search for
  23488. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23489. */
  23490. Scene.prototype.getMeshByID = function (id) {
  23491. for (var index = 0; index < this.meshes.length; index++) {
  23492. if (this.meshes[index].id === id) {
  23493. return this.meshes[index];
  23494. }
  23495. }
  23496. return null;
  23497. };
  23498. Scene.prototype.getMeshesByID = function (id) {
  23499. return this.meshes.filter(function (m) {
  23500. return m.id === id;
  23501. });
  23502. };
  23503. /**
  23504. * Get the first added transform node found of a given ID
  23505. * @param {string} id - the id to search for
  23506. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23507. */
  23508. Scene.prototype.getTransformNodeByID = function (id) {
  23509. for (var index = 0; index < this.transformNodes.length; index++) {
  23510. if (this.transformNodes[index].id === id) {
  23511. return this.transformNodes[index];
  23512. }
  23513. }
  23514. return null;
  23515. };
  23516. Scene.prototype.getTransformNodesByID = function (id) {
  23517. return this.transformNodes.filter(function (m) {
  23518. return m.id === id;
  23519. });
  23520. };
  23521. /**
  23522. * Get a mesh with its auto-generated unique id
  23523. * @param {number} uniqueId - the unique id to search for
  23524. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23525. */
  23526. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23527. for (var index = 0; index < this.meshes.length; index++) {
  23528. if (this.meshes[index].uniqueId === uniqueId) {
  23529. return this.meshes[index];
  23530. }
  23531. }
  23532. return null;
  23533. };
  23534. /**
  23535. * Get a the last added mesh found of a given ID
  23536. * @param {string} id - the id to search for
  23537. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23538. */
  23539. Scene.prototype.getLastMeshByID = function (id) {
  23540. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23541. if (this.meshes[index].id === id) {
  23542. return this.meshes[index];
  23543. }
  23544. }
  23545. return null;
  23546. };
  23547. /**
  23548. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23549. * @param {string} id - the id to search for
  23550. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23551. */
  23552. Scene.prototype.getLastEntryByID = function (id) {
  23553. var index;
  23554. for (index = this.meshes.length - 1; index >= 0; index--) {
  23555. if (this.meshes[index].id === id) {
  23556. return this.meshes[index];
  23557. }
  23558. }
  23559. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23560. if (this.transformNodes[index].id === id) {
  23561. return this.transformNodes[index];
  23562. }
  23563. }
  23564. for (index = this.cameras.length - 1; index >= 0; index--) {
  23565. if (this.cameras[index].id === id) {
  23566. return this.cameras[index];
  23567. }
  23568. }
  23569. for (index = this.lights.length - 1; index >= 0; index--) {
  23570. if (this.lights[index].id === id) {
  23571. return this.lights[index];
  23572. }
  23573. }
  23574. return null;
  23575. };
  23576. Scene.prototype.getNodeByID = function (id) {
  23577. var mesh = this.getMeshByID(id);
  23578. if (mesh) {
  23579. return mesh;
  23580. }
  23581. var light = this.getLightByID(id);
  23582. if (light) {
  23583. return light;
  23584. }
  23585. var camera = this.getCameraByID(id);
  23586. if (camera) {
  23587. return camera;
  23588. }
  23589. var bone = this.getBoneByID(id);
  23590. return bone;
  23591. };
  23592. Scene.prototype.getNodeByName = function (name) {
  23593. var mesh = this.getMeshByName(name);
  23594. if (mesh) {
  23595. return mesh;
  23596. }
  23597. var light = this.getLightByName(name);
  23598. if (light) {
  23599. return light;
  23600. }
  23601. var camera = this.getCameraByName(name);
  23602. if (camera) {
  23603. return camera;
  23604. }
  23605. var bone = this.getBoneByName(name);
  23606. return bone;
  23607. };
  23608. Scene.prototype.getMeshByName = function (name) {
  23609. for (var index = 0; index < this.meshes.length; index++) {
  23610. if (this.meshes[index].name === name) {
  23611. return this.meshes[index];
  23612. }
  23613. }
  23614. return null;
  23615. };
  23616. Scene.prototype.getTransformNodeByName = function (name) {
  23617. for (var index = 0; index < this.transformNodes.length; index++) {
  23618. if (this.transformNodes[index].name === name) {
  23619. return this.transformNodes[index];
  23620. }
  23621. }
  23622. return null;
  23623. };
  23624. Scene.prototype.getSoundByName = function (name) {
  23625. var index;
  23626. if (BABYLON.AudioEngine) {
  23627. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23628. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23629. return this.mainSoundTrack.soundCollection[index];
  23630. }
  23631. }
  23632. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23633. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23634. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23635. return this.soundTracks[sdIndex].soundCollection[index];
  23636. }
  23637. }
  23638. }
  23639. }
  23640. return null;
  23641. };
  23642. Scene.prototype.getLastSkeletonByID = function (id) {
  23643. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23644. if (this.skeletons[index].id === id) {
  23645. return this.skeletons[index];
  23646. }
  23647. }
  23648. return null;
  23649. };
  23650. Scene.prototype.getSkeletonById = function (id) {
  23651. for (var index = 0; index < this.skeletons.length; index++) {
  23652. if (this.skeletons[index].id === id) {
  23653. return this.skeletons[index];
  23654. }
  23655. }
  23656. return null;
  23657. };
  23658. Scene.prototype.getSkeletonByName = function (name) {
  23659. for (var index = 0; index < this.skeletons.length; index++) {
  23660. if (this.skeletons[index].name === name) {
  23661. return this.skeletons[index];
  23662. }
  23663. }
  23664. return null;
  23665. };
  23666. Scene.prototype.getMorphTargetManagerById = function (id) {
  23667. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23668. if (this.morphTargetManagers[index].uniqueId === id) {
  23669. return this.morphTargetManagers[index];
  23670. }
  23671. }
  23672. return null;
  23673. };
  23674. Scene.prototype.isActiveMesh = function (mesh) {
  23675. return (this._activeMeshes.indexOf(mesh) !== -1);
  23676. };
  23677. /**
  23678. * Return a the first highlight layer of the scene with a given name.
  23679. * @param name The name of the highlight layer to look for.
  23680. * @return The highlight layer if found otherwise null.
  23681. */
  23682. Scene.prototype.getHighlightLayerByName = function (name) {
  23683. for (var index = 0; index < this.effectLayers.length; index++) {
  23684. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23685. return this.effectLayers[index];
  23686. }
  23687. }
  23688. return null;
  23689. };
  23690. /**
  23691. * Return a the first highlight layer of the scene with a given name.
  23692. * @param name The name of the highlight layer to look for.
  23693. * @return The highlight layer if found otherwise null.
  23694. */
  23695. Scene.prototype.getGlowLayerByName = function (name) {
  23696. for (var index = 0; index < this.effectLayers.length; index++) {
  23697. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23698. return this.effectLayers[index];
  23699. }
  23700. }
  23701. return null;
  23702. };
  23703. Object.defineProperty(Scene.prototype, "uid", {
  23704. /**
  23705. * Return a unique id as a string which can serve as an identifier for the scene
  23706. */
  23707. get: function () {
  23708. if (!this._uid) {
  23709. this._uid = BABYLON.Tools.RandomId();
  23710. }
  23711. return this._uid;
  23712. },
  23713. enumerable: true,
  23714. configurable: true
  23715. });
  23716. /**
  23717. * Add an externaly attached data from its key.
  23718. * This method call will fail and return false, if such key already exists.
  23719. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23720. * @param key the unique key that identifies the data
  23721. * @param data the data object to associate to the key for this Engine instance
  23722. * @return true if no such key were already present and the data was added successfully, false otherwise
  23723. */
  23724. Scene.prototype.addExternalData = function (key, data) {
  23725. if (!this._externalData) {
  23726. this._externalData = new BABYLON.StringDictionary();
  23727. }
  23728. return this._externalData.add(key, data);
  23729. };
  23730. /**
  23731. * Get an externaly attached data from its key
  23732. * @param key the unique key that identifies the data
  23733. * @return the associated data, if present (can be null), or undefined if not present
  23734. */
  23735. Scene.prototype.getExternalData = function (key) {
  23736. if (!this._externalData) {
  23737. return null;
  23738. }
  23739. return this._externalData.get(key);
  23740. };
  23741. /**
  23742. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23743. * @param key the unique key that identifies the data
  23744. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23745. * @return the associated data, can be null if the factory returned null.
  23746. */
  23747. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23748. if (!this._externalData) {
  23749. this._externalData = new BABYLON.StringDictionary();
  23750. }
  23751. return this._externalData.getOrAddWithFactory(key, factory);
  23752. };
  23753. /**
  23754. * Remove an externaly attached data from the Engine instance
  23755. * @param key the unique key that identifies the data
  23756. * @return true if the data was successfully removed, false if it doesn't exist
  23757. */
  23758. Scene.prototype.removeExternalData = function (key) {
  23759. return this._externalData.remove(key);
  23760. };
  23761. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23762. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23763. if (mesh.showSubMeshesBoundingBox) {
  23764. var boundingInfo = subMesh.getBoundingInfo();
  23765. if (boundingInfo !== null && boundingInfo !== undefined) {
  23766. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23767. }
  23768. }
  23769. var material = subMesh.getMaterial();
  23770. if (material !== null && material !== undefined) {
  23771. // Render targets
  23772. if (material.getRenderTargetTextures !== undefined) {
  23773. if (this._processedMaterials.indexOf(material) === -1) {
  23774. this._processedMaterials.push(material);
  23775. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23776. }
  23777. }
  23778. // Dispatch
  23779. this._activeIndices.addCount(subMesh.indexCount, false);
  23780. this._renderingManager.dispatch(subMesh, mesh, material);
  23781. }
  23782. }
  23783. };
  23784. Scene.prototype._isInIntermediateRendering = function () {
  23785. return this._intermediateRendering;
  23786. };
  23787. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23788. this._activeMeshCandidateProvider = provider;
  23789. };
  23790. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23791. return this._activeMeshCandidateProvider;
  23792. };
  23793. /**
  23794. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23795. */
  23796. Scene.prototype.freezeActiveMeshes = function () {
  23797. this._evaluateActiveMeshes();
  23798. this._activeMeshesFrozen = true;
  23799. return this;
  23800. };
  23801. /**
  23802. * Use this function to restart evaluating active meshes on every frame
  23803. */
  23804. Scene.prototype.unfreezeActiveMeshes = function () {
  23805. this._activeMeshesFrozen = false;
  23806. return this;
  23807. };
  23808. Scene.prototype._evaluateActiveMeshes = function () {
  23809. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23810. return;
  23811. }
  23812. if (!this.activeCamera) {
  23813. return;
  23814. }
  23815. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23816. this.activeCamera._activeMeshes.reset();
  23817. this._activeMeshes.reset();
  23818. this._renderingManager.reset();
  23819. this._processedMaterials.reset();
  23820. this._activeParticleSystems.reset();
  23821. this._activeSkeletons.reset();
  23822. this._softwareSkinnedMeshes.reset();
  23823. if (this._boundingBoxRenderer) {
  23824. this._boundingBoxRenderer.reset();
  23825. }
  23826. // Meshes
  23827. var meshes;
  23828. var len;
  23829. var checkIsEnabled = true;
  23830. // Determine mesh candidates
  23831. if (this._activeMeshCandidateProvider !== undefined) {
  23832. // Use _activeMeshCandidateProvider
  23833. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23834. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23835. if (meshes !== undefined) {
  23836. len = meshes.length;
  23837. }
  23838. else {
  23839. len = 0;
  23840. }
  23841. }
  23842. else if (this._selectionOctree !== undefined) {
  23843. // Octree
  23844. var selection = this._selectionOctree.select(this._frustumPlanes);
  23845. meshes = selection.data;
  23846. len = selection.length;
  23847. }
  23848. else {
  23849. // Full scene traversal
  23850. len = this.meshes.length;
  23851. meshes = this.meshes;
  23852. }
  23853. // Check each mesh
  23854. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23855. mesh = meshes[meshIndex];
  23856. if (mesh.isBlocked) {
  23857. continue;
  23858. }
  23859. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23860. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23861. continue;
  23862. }
  23863. mesh.computeWorldMatrix();
  23864. // Intersections
  23865. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23866. this._meshesForIntersections.pushNoDuplicate(mesh);
  23867. }
  23868. // Switch to current LOD
  23869. meshLOD = mesh.getLOD(this.activeCamera);
  23870. if (meshLOD === undefined || meshLOD === null) {
  23871. continue;
  23872. }
  23873. mesh._preActivate();
  23874. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23875. this._activeMeshes.push(mesh);
  23876. this.activeCamera._activeMeshes.push(mesh);
  23877. mesh._activate(this._renderId);
  23878. if (meshLOD !== mesh) {
  23879. meshLOD._activate(this._renderId);
  23880. }
  23881. this._activeMesh(mesh, meshLOD);
  23882. }
  23883. }
  23884. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23885. // Particle systems
  23886. if (this.particlesEnabled) {
  23887. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23888. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23889. var particleSystem = this.particleSystems[particleIndex];
  23890. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23891. continue;
  23892. }
  23893. var emitter = particleSystem.emitter;
  23894. if (!emitter.position || emitter.isEnabled()) {
  23895. this._activeParticleSystems.push(particleSystem);
  23896. particleSystem.animate();
  23897. this._renderingManager.dispatchParticles(particleSystem);
  23898. }
  23899. }
  23900. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23901. }
  23902. };
  23903. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23904. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23905. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23906. mesh.skeleton.prepare();
  23907. }
  23908. if (!mesh.computeBonesUsingShaders) {
  23909. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23910. }
  23911. }
  23912. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23913. var boundingInfo = sourceMesh.getBoundingInfo();
  23914. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23915. }
  23916. if (mesh !== undefined && mesh !== null
  23917. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23918. // Submeshes Octrees
  23919. var len;
  23920. var subMeshes;
  23921. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23922. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23923. len = intersections.length;
  23924. subMeshes = intersections.data;
  23925. }
  23926. else {
  23927. subMeshes = mesh.subMeshes;
  23928. len = subMeshes.length;
  23929. }
  23930. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23931. subMesh = subMeshes[subIndex];
  23932. this._evaluateSubMesh(subMesh, mesh);
  23933. }
  23934. }
  23935. };
  23936. Scene.prototype.updateTransformMatrix = function (force) {
  23937. if (!this.activeCamera) {
  23938. return;
  23939. }
  23940. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23941. };
  23942. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23943. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23944. };
  23945. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23946. if (camera && camera._skipRendering) {
  23947. return;
  23948. }
  23949. var engine = this._engine;
  23950. this.activeCamera = camera;
  23951. if (!this.activeCamera)
  23952. throw new Error("Active camera not set");
  23953. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23954. // Viewport
  23955. engine.setViewport(this.activeCamera.viewport);
  23956. // Camera
  23957. this.resetCachedMaterial();
  23958. this._renderId++;
  23959. this.activeCamera.update();
  23960. this.updateTransformMatrix();
  23961. if (camera._alternateCamera) {
  23962. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23963. this._alternateRendering = true;
  23964. }
  23965. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23966. // Meshes
  23967. this._evaluateActiveMeshes();
  23968. // Software skinning
  23969. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23970. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23971. mesh.applySkeleton(mesh.skeleton);
  23972. }
  23973. // Render targets
  23974. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23975. var needsRestoreFrameBuffer = false;
  23976. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23977. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23978. }
  23979. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23980. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23981. }
  23982. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23983. this._intermediateRendering = true;
  23984. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23985. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23986. var renderTarget = this._renderTargets.data[renderIndex];
  23987. if (renderTarget._shouldRender()) {
  23988. this._renderId++;
  23989. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23990. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23991. }
  23992. }
  23993. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23994. this._intermediateRendering = false;
  23995. this._renderId++;
  23996. needsRestoreFrameBuffer = true; // Restore back buffer
  23997. }
  23998. // Render EffecttLayer Texture
  23999. var stencilState = this._engine.getStencilBuffer();
  24000. var renderEffects = false;
  24001. var needStencil = false;
  24002. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24003. this._intermediateRendering = true;
  24004. for (var i = 0; i < this.effectLayers.length; i++) {
  24005. var effectLayer = this.effectLayers[i];
  24006. if (effectLayer.shouldRender() &&
  24007. (!effectLayer.camera ||
  24008. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24009. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24010. renderEffects = true;
  24011. needStencil = needStencil || effectLayer.needStencil();
  24012. var renderTarget = effectLayer._mainTexture;
  24013. if (renderTarget._shouldRender()) {
  24014. this._renderId++;
  24015. renderTarget.render(false, false);
  24016. needsRestoreFrameBuffer = true;
  24017. }
  24018. }
  24019. }
  24020. this._intermediateRendering = false;
  24021. this._renderId++;
  24022. }
  24023. if (needsRestoreFrameBuffer) {
  24024. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24025. }
  24026. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24027. // Prepare Frame
  24028. this.postProcessManager._prepareFrame();
  24029. // Backgrounds
  24030. var layerIndex;
  24031. var layer;
  24032. if (this.layers.length) {
  24033. engine.setDepthBuffer(false);
  24034. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24035. layer = this.layers[layerIndex];
  24036. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24037. layer.render();
  24038. }
  24039. }
  24040. engine.setDepthBuffer(true);
  24041. }
  24042. // Activate effect Layer stencil
  24043. if (needStencil) {
  24044. this._engine.setStencilBuffer(true);
  24045. }
  24046. // Render
  24047. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24048. this._renderingManager.render(null, null, true, true);
  24049. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24050. // Restore effect Layer stencil
  24051. if (needStencil) {
  24052. this._engine.setStencilBuffer(stencilState);
  24053. }
  24054. // Bounding boxes
  24055. if (this._boundingBoxRenderer) {
  24056. this._boundingBoxRenderer.render();
  24057. }
  24058. // Lens flares
  24059. if (this.lensFlaresEnabled) {
  24060. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24061. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24062. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24063. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24064. lensFlareSystem.render();
  24065. }
  24066. }
  24067. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24068. }
  24069. // Foregrounds
  24070. if (this.layers.length) {
  24071. engine.setDepthBuffer(false);
  24072. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24073. layer = this.layers[layerIndex];
  24074. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24075. layer.render();
  24076. }
  24077. }
  24078. engine.setDepthBuffer(true);
  24079. }
  24080. // Effect Layer
  24081. if (renderEffects) {
  24082. engine.setDepthBuffer(false);
  24083. for (var i = 0; i < this.effectLayers.length; i++) {
  24084. if (this.effectLayers[i].shouldRender()) {
  24085. this.effectLayers[i].render();
  24086. }
  24087. }
  24088. engine.setDepthBuffer(true);
  24089. }
  24090. // Finalize frame
  24091. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24092. // Reset some special arrays
  24093. this._renderTargets.reset();
  24094. this._alternateRendering = false;
  24095. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24096. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24097. };
  24098. Scene.prototype._processSubCameras = function (camera) {
  24099. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24100. this._renderForCamera(camera);
  24101. return;
  24102. }
  24103. // Update camera
  24104. if (this.activeCamera) {
  24105. this.activeCamera.update();
  24106. }
  24107. // rig cameras
  24108. for (var index = 0; index < camera._rigCameras.length; index++) {
  24109. this._renderForCamera(camera._rigCameras[index], camera);
  24110. }
  24111. this.activeCamera = camera;
  24112. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24113. };
  24114. Scene.prototype._checkIntersections = function () {
  24115. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24116. var sourceMesh = this._meshesForIntersections.data[index];
  24117. if (!sourceMesh.actionManager) {
  24118. continue;
  24119. }
  24120. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24121. var action = sourceMesh.actionManager.actions[actionIndex];
  24122. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24123. var parameters = action.getTriggerParameter();
  24124. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24125. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24126. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24127. if (areIntersecting && currentIntersectionInProgress === -1) {
  24128. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24129. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24130. sourceMesh._intersectionsInProgress.push(otherMesh);
  24131. }
  24132. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24133. sourceMesh._intersectionsInProgress.push(otherMesh);
  24134. }
  24135. }
  24136. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24137. //They intersected, and now they don't.
  24138. //is this trigger an exit trigger? execute an event.
  24139. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24140. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24141. }
  24142. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24143. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24144. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24145. }
  24146. }
  24147. }
  24148. }
  24149. }
  24150. };
  24151. Scene.prototype.render = function () {
  24152. if (this.isDisposed) {
  24153. return;
  24154. }
  24155. this._activeParticles.fetchNewFrame();
  24156. this._totalVertices.fetchNewFrame();
  24157. this._activeIndices.fetchNewFrame();
  24158. this._activeBones.fetchNewFrame();
  24159. this._meshesForIntersections.reset();
  24160. this.resetCachedMaterial();
  24161. this.onBeforeAnimationsObservable.notifyObservers(this);
  24162. // Actions
  24163. if (this.actionManager) {
  24164. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24165. }
  24166. //Simplification Queue
  24167. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24168. this.simplificationQueue.executeNext();
  24169. }
  24170. if (this._engine.isDeterministicLockStep()) {
  24171. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24172. var defaultFPS = (60.0 / 1000.0);
  24173. var defaultFrameTime = 1000 / 60; // frame time in MS
  24174. if (this._physicsEngine) {
  24175. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24176. }
  24177. var stepsTaken = 0;
  24178. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24179. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24180. internalSteps = Math.min(internalSteps, maxSubSteps);
  24181. do {
  24182. this.onBeforeStepObservable.notifyObservers(this);
  24183. // Animations
  24184. this._animationRatio = defaultFrameTime * defaultFPS;
  24185. this._animate();
  24186. this.onAfterAnimationsObservable.notifyObservers(this);
  24187. // Physics
  24188. if (this._physicsEngine) {
  24189. this.onBeforePhysicsObservable.notifyObservers(this);
  24190. this._physicsEngine._step(defaultFrameTime / 1000);
  24191. this.onAfterPhysicsObservable.notifyObservers(this);
  24192. }
  24193. this.onAfterStepObservable.notifyObservers(this);
  24194. this._currentStepId++;
  24195. stepsTaken++;
  24196. deltaTime -= defaultFrameTime;
  24197. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24198. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24199. }
  24200. else {
  24201. // Animations
  24202. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24203. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24204. this._animate();
  24205. this.onAfterAnimationsObservable.notifyObservers(this);
  24206. // Physics
  24207. if (this._physicsEngine) {
  24208. this.onBeforePhysicsObservable.notifyObservers(this);
  24209. this._physicsEngine._step(deltaTime / 1000.0);
  24210. this.onAfterPhysicsObservable.notifyObservers(this);
  24211. }
  24212. }
  24213. // update gamepad manager
  24214. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24215. this._gamepadManager._checkGamepadsStatus();
  24216. }
  24217. // Before render
  24218. this.onBeforeRenderObservable.notifyObservers(this);
  24219. // Customs render targets
  24220. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24221. var engine = this.getEngine();
  24222. var currentActiveCamera = this.activeCamera;
  24223. if (this.renderTargetsEnabled) {
  24224. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24225. this._intermediateRendering = true;
  24226. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24227. var renderTarget = this.customRenderTargets[customIndex];
  24228. if (renderTarget._shouldRender()) {
  24229. this._renderId++;
  24230. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24231. if (!this.activeCamera)
  24232. throw new Error("Active camera not set");
  24233. // Viewport
  24234. engine.setViewport(this.activeCamera.viewport);
  24235. // Camera
  24236. this.updateTransformMatrix();
  24237. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24238. }
  24239. }
  24240. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24241. this._intermediateRendering = false;
  24242. this._renderId++;
  24243. }
  24244. // Restore back buffer
  24245. if (this.customRenderTargets.length > 0) {
  24246. engine.restoreDefaultFramebuffer();
  24247. }
  24248. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24249. this.activeCamera = currentActiveCamera;
  24250. // Procedural textures
  24251. if (this.proceduralTexturesEnabled) {
  24252. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24253. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24254. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24255. if (proceduralTexture._shouldRender()) {
  24256. proceduralTexture.render();
  24257. }
  24258. }
  24259. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24260. }
  24261. // Clear
  24262. if (this.autoClearDepthAndStencil || this.autoClear) {
  24263. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24264. }
  24265. // Shadows
  24266. if (this.shadowsEnabled) {
  24267. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24268. var light = this.lights[lightIndex];
  24269. var shadowGenerator = light.getShadowGenerator();
  24270. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24271. var shadowMap = (shadowGenerator.getShadowMap());
  24272. if (this.textures.indexOf(shadowMap) !== -1) {
  24273. this._renderTargets.push(shadowMap);
  24274. }
  24275. }
  24276. }
  24277. }
  24278. // Depth renderer
  24279. for (var key in this._depthRenderer) {
  24280. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24281. }
  24282. // Geometry renderer
  24283. if (this._geometryBufferRenderer) {
  24284. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24285. }
  24286. // RenderPipeline
  24287. if (this._postProcessRenderPipelineManager) {
  24288. this._postProcessRenderPipelineManager.update();
  24289. }
  24290. // Multi-cameras?
  24291. if (this.activeCameras.length > 0) {
  24292. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24293. if (cameraIndex > 0) {
  24294. this._engine.clear(null, false, true, true);
  24295. }
  24296. this._processSubCameras(this.activeCameras[cameraIndex]);
  24297. }
  24298. }
  24299. else {
  24300. if (!this.activeCamera) {
  24301. throw new Error("No camera defined");
  24302. }
  24303. this._processSubCameras(this.activeCamera);
  24304. }
  24305. // Intersection checks
  24306. this._checkIntersections();
  24307. // Update the audio listener attached to the camera
  24308. if (BABYLON.AudioEngine) {
  24309. this._updateAudioParameters();
  24310. }
  24311. // After render
  24312. if (this.afterRender) {
  24313. this.afterRender();
  24314. }
  24315. this.onAfterRenderObservable.notifyObservers(this);
  24316. // Cleaning
  24317. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24318. var data = this._toBeDisposed.data[index];
  24319. if (data) {
  24320. data.dispose();
  24321. }
  24322. this._toBeDisposed[index] = null;
  24323. }
  24324. this._toBeDisposed.reset();
  24325. if (this.dumpNextRenderTargets) {
  24326. this.dumpNextRenderTargets = false;
  24327. }
  24328. this._activeBones.addCount(0, true);
  24329. this._activeIndices.addCount(0, true);
  24330. this._activeParticles.addCount(0, true);
  24331. };
  24332. Scene.prototype._updateAudioParameters = function () {
  24333. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24334. return;
  24335. }
  24336. var listeningCamera;
  24337. var audioEngine = BABYLON.Engine.audioEngine;
  24338. if (this.activeCameras.length > 0) {
  24339. listeningCamera = this.activeCameras[0];
  24340. }
  24341. else {
  24342. listeningCamera = this.activeCamera;
  24343. }
  24344. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24345. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24346. // for VR cameras
  24347. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24348. listeningCamera = listeningCamera.rigCameras[0];
  24349. }
  24350. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24351. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24352. cameraDirection.normalize();
  24353. // To avoid some errors on GearVR
  24354. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24355. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24356. }
  24357. var i;
  24358. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24359. var sound = this.mainSoundTrack.soundCollection[i];
  24360. if (sound.useCustomAttenuation) {
  24361. sound.updateDistanceFromListener();
  24362. }
  24363. }
  24364. for (i = 0; i < this.soundTracks.length; i++) {
  24365. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24366. sound = this.soundTracks[i].soundCollection[j];
  24367. if (sound.useCustomAttenuation) {
  24368. sound.updateDistanceFromListener();
  24369. }
  24370. }
  24371. }
  24372. }
  24373. };
  24374. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24375. // Audio
  24376. get: function () {
  24377. return this._audioEnabled;
  24378. },
  24379. set: function (value) {
  24380. this._audioEnabled = value;
  24381. if (BABYLON.AudioEngine) {
  24382. if (this._audioEnabled) {
  24383. this._enableAudio();
  24384. }
  24385. else {
  24386. this._disableAudio();
  24387. }
  24388. }
  24389. },
  24390. enumerable: true,
  24391. configurable: true
  24392. });
  24393. Scene.prototype._disableAudio = function () {
  24394. var i;
  24395. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24396. this.mainSoundTrack.soundCollection[i].pause();
  24397. }
  24398. for (i = 0; i < this.soundTracks.length; i++) {
  24399. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24400. this.soundTracks[i].soundCollection[j].pause();
  24401. }
  24402. }
  24403. };
  24404. Scene.prototype._enableAudio = function () {
  24405. var i;
  24406. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24407. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24408. this.mainSoundTrack.soundCollection[i].play();
  24409. }
  24410. }
  24411. for (i = 0; i < this.soundTracks.length; i++) {
  24412. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24413. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24414. this.soundTracks[i].soundCollection[j].play();
  24415. }
  24416. }
  24417. }
  24418. };
  24419. Object.defineProperty(Scene.prototype, "headphone", {
  24420. get: function () {
  24421. return this._headphone;
  24422. },
  24423. set: function (value) {
  24424. this._headphone = value;
  24425. if (BABYLON.AudioEngine) {
  24426. if (this._headphone) {
  24427. this._switchAudioModeForHeadphones();
  24428. }
  24429. else {
  24430. this._switchAudioModeForNormalSpeakers();
  24431. }
  24432. }
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Scene.prototype._switchAudioModeForHeadphones = function () {
  24438. this.mainSoundTrack.switchPanningModelToHRTF();
  24439. for (var i = 0; i < this.soundTracks.length; i++) {
  24440. this.soundTracks[i].switchPanningModelToHRTF();
  24441. }
  24442. };
  24443. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24444. this.mainSoundTrack.switchPanningModelToEqualPower();
  24445. for (var i = 0; i < this.soundTracks.length; i++) {
  24446. this.soundTracks[i].switchPanningModelToEqualPower();
  24447. }
  24448. };
  24449. /**
  24450. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24451. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24452. * @returns the created depth renderer
  24453. */
  24454. Scene.prototype.enableDepthRenderer = function (camera) {
  24455. camera = camera || this.activeCamera;
  24456. if (!camera) {
  24457. throw "No camera available to enable depth renderer";
  24458. }
  24459. if (!this._depthRenderer[camera.id]) {
  24460. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24461. }
  24462. return this._depthRenderer[camera.id];
  24463. };
  24464. /**
  24465. * Disables a depth renderer for a given camera
  24466. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24467. */
  24468. Scene.prototype.disableDepthRenderer = function (camera) {
  24469. camera = camera || this.activeCamera;
  24470. if (!camera || !this._depthRenderer[camera.id]) {
  24471. return;
  24472. }
  24473. this._depthRenderer[camera.id].dispose();
  24474. delete this._depthRenderer[camera.id];
  24475. };
  24476. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24477. if (ratio === void 0) { ratio = 1; }
  24478. if (this._geometryBufferRenderer) {
  24479. return this._geometryBufferRenderer;
  24480. }
  24481. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24482. if (!this._geometryBufferRenderer.isSupported) {
  24483. this._geometryBufferRenderer = null;
  24484. }
  24485. return this._geometryBufferRenderer;
  24486. };
  24487. Scene.prototype.disableGeometryBufferRenderer = function () {
  24488. if (!this._geometryBufferRenderer) {
  24489. return;
  24490. }
  24491. this._geometryBufferRenderer.dispose();
  24492. this._geometryBufferRenderer = null;
  24493. };
  24494. Scene.prototype.freezeMaterials = function () {
  24495. for (var i = 0; i < this.materials.length; i++) {
  24496. this.materials[i].freeze();
  24497. }
  24498. };
  24499. Scene.prototype.unfreezeMaterials = function () {
  24500. for (var i = 0; i < this.materials.length; i++) {
  24501. this.materials[i].unfreeze();
  24502. }
  24503. };
  24504. Scene.prototype.dispose = function () {
  24505. this.beforeRender = null;
  24506. this.afterRender = null;
  24507. this.skeletons = [];
  24508. this.morphTargetManagers = [];
  24509. this.importedMeshesFiles = new Array();
  24510. this.stopAllAnimations();
  24511. this.resetCachedMaterial();
  24512. for (var key in this._depthRenderer) {
  24513. this._depthRenderer[key].dispose();
  24514. }
  24515. if (this._gamepadManager) {
  24516. this._gamepadManager.dispose();
  24517. this._gamepadManager = null;
  24518. }
  24519. // Smart arrays
  24520. if (this.activeCamera) {
  24521. this.activeCamera._activeMeshes.dispose();
  24522. this.activeCamera = null;
  24523. }
  24524. this._activeMeshes.dispose();
  24525. this._renderingManager.dispose();
  24526. this._processedMaterials.dispose();
  24527. this._activeParticleSystems.dispose();
  24528. this._activeSkeletons.dispose();
  24529. this._softwareSkinnedMeshes.dispose();
  24530. this._renderTargets.dispose();
  24531. if (this._boundingBoxRenderer) {
  24532. this._boundingBoxRenderer.dispose();
  24533. }
  24534. this._meshesForIntersections.dispose();
  24535. this._toBeDisposed.dispose();
  24536. // Abort active requests
  24537. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24538. var request = _a[_i];
  24539. request.abort();
  24540. }
  24541. // Debug layer
  24542. if (this._debugLayer) {
  24543. this._debugLayer.hide();
  24544. }
  24545. // Events
  24546. this.onDisposeObservable.notifyObservers(this);
  24547. this.onDisposeObservable.clear();
  24548. this.onBeforeRenderObservable.clear();
  24549. this.onAfterRenderObservable.clear();
  24550. this.OnBeforeRenderTargetsRenderObservable.clear();
  24551. this.OnAfterRenderTargetsRenderObservable.clear();
  24552. this.onAfterStepObservable.clear();
  24553. this.onBeforeStepObservable.clear();
  24554. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24555. this.onAfterActiveMeshesEvaluationObservable.clear();
  24556. this.onBeforeParticlesRenderingObservable.clear();
  24557. this.onAfterParticlesRenderingObservable.clear();
  24558. this.onBeforeSpritesRenderingObservable.clear();
  24559. this.onAfterSpritesRenderingObservable.clear();
  24560. this.onBeforeDrawPhaseObservable.clear();
  24561. this.onAfterDrawPhaseObservable.clear();
  24562. this.onBeforePhysicsObservable.clear();
  24563. this.onAfterPhysicsObservable.clear();
  24564. this.onBeforeAnimationsObservable.clear();
  24565. this.onAfterAnimationsObservable.clear();
  24566. this.onDataLoadedObservable.clear();
  24567. this.detachControl();
  24568. // Release sounds & sounds tracks
  24569. if (BABYLON.AudioEngine) {
  24570. this.disposeSounds();
  24571. }
  24572. // VR Helper
  24573. if (this.VRHelper) {
  24574. this.VRHelper.dispose();
  24575. }
  24576. // Detach cameras
  24577. var canvas = this._engine.getRenderingCanvas();
  24578. if (canvas) {
  24579. var index;
  24580. for (index = 0; index < this.cameras.length; index++) {
  24581. this.cameras[index].detachControl(canvas);
  24582. }
  24583. }
  24584. // Release animation groups
  24585. while (this.animationGroups.length) {
  24586. this.animationGroups[0].dispose();
  24587. }
  24588. // Release lights
  24589. while (this.lights.length) {
  24590. this.lights[0].dispose();
  24591. }
  24592. // Release meshes
  24593. while (this.meshes.length) {
  24594. this.meshes[0].dispose(true);
  24595. }
  24596. while (this.transformNodes.length) {
  24597. this.removeTransformNode(this.transformNodes[0]);
  24598. }
  24599. // Release cameras
  24600. while (this.cameras.length) {
  24601. this.cameras[0].dispose();
  24602. }
  24603. // Release materials
  24604. if (this.defaultMaterial) {
  24605. this.defaultMaterial.dispose();
  24606. }
  24607. while (this.multiMaterials.length) {
  24608. this.multiMaterials[0].dispose();
  24609. }
  24610. while (this.materials.length) {
  24611. this.materials[0].dispose();
  24612. }
  24613. // Release particles
  24614. while (this.particleSystems.length) {
  24615. this.particleSystems[0].dispose();
  24616. }
  24617. // Release sprites
  24618. while (this.spriteManagers.length) {
  24619. this.spriteManagers[0].dispose();
  24620. }
  24621. // Release postProcesses
  24622. while (this.postProcesses.length) {
  24623. this.postProcesses[0].dispose();
  24624. }
  24625. // Release layers
  24626. while (this.layers.length) {
  24627. this.layers[0].dispose();
  24628. }
  24629. while (this.effectLayers.length) {
  24630. this.effectLayers[0].dispose();
  24631. }
  24632. // Release textures
  24633. while (this.textures.length) {
  24634. this.textures[0].dispose();
  24635. }
  24636. // Release UBO
  24637. this._sceneUbo.dispose();
  24638. if (this._alternateSceneUbo) {
  24639. this._alternateSceneUbo.dispose();
  24640. }
  24641. // Post-processes
  24642. this.postProcessManager.dispose();
  24643. if (this._postProcessRenderPipelineManager) {
  24644. this._postProcessRenderPipelineManager.dispose();
  24645. }
  24646. // Physics
  24647. if (this._physicsEngine) {
  24648. this.disablePhysicsEngine();
  24649. }
  24650. // Remove from engine
  24651. index = this._engine.scenes.indexOf(this);
  24652. if (index > -1) {
  24653. this._engine.scenes.splice(index, 1);
  24654. }
  24655. this._engine.wipeCaches(true);
  24656. this._isDisposed = true;
  24657. };
  24658. Object.defineProperty(Scene.prototype, "isDisposed", {
  24659. get: function () {
  24660. return this._isDisposed;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. // Release sounds & sounds tracks
  24666. Scene.prototype.disposeSounds = function () {
  24667. if (!this._mainSoundTrack) {
  24668. return;
  24669. }
  24670. this.mainSoundTrack.dispose();
  24671. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24672. this.soundTracks[scIndex].dispose();
  24673. }
  24674. };
  24675. // Octrees
  24676. /**
  24677. * Get the world extend vectors with an optional filter
  24678. *
  24679. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24680. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24681. */
  24682. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24683. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24684. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24685. filterPredicate = filterPredicate || (function () { return true; });
  24686. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24687. mesh.computeWorldMatrix(true);
  24688. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24689. return;
  24690. }
  24691. var boundingInfo = mesh.getBoundingInfo();
  24692. var minBox = boundingInfo.boundingBox.minimumWorld;
  24693. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24694. BABYLON.Tools.CheckExtends(minBox, min, max);
  24695. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24696. });
  24697. return {
  24698. min: min,
  24699. max: max
  24700. };
  24701. };
  24702. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24703. if (maxCapacity === void 0) { maxCapacity = 64; }
  24704. if (maxDepth === void 0) { maxDepth = 2; }
  24705. if (!this._selectionOctree) {
  24706. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24707. }
  24708. var worldExtends = this.getWorldExtends();
  24709. // Update octree
  24710. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24711. return this._selectionOctree;
  24712. };
  24713. // Picking
  24714. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24715. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24716. var result = BABYLON.Ray.Zero();
  24717. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24718. return result;
  24719. };
  24720. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24721. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24722. var engine = this._engine;
  24723. if (!camera) {
  24724. if (!this.activeCamera)
  24725. throw new Error("Active camera not set");
  24726. camera = this.activeCamera;
  24727. }
  24728. var cameraViewport = camera.viewport;
  24729. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24730. // Moving coordinates to local viewport world
  24731. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24732. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24733. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24734. return this;
  24735. };
  24736. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24737. var result = BABYLON.Ray.Zero();
  24738. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24739. return result;
  24740. };
  24741. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24742. if (!BABYLON.PickingInfo) {
  24743. return this;
  24744. }
  24745. var engine = this._engine;
  24746. if (!camera) {
  24747. if (!this.activeCamera)
  24748. throw new Error("Active camera not set");
  24749. camera = this.activeCamera;
  24750. }
  24751. var cameraViewport = camera.viewport;
  24752. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24753. var identity = BABYLON.Matrix.Identity();
  24754. // Moving coordinates to local viewport world
  24755. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24756. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24757. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24758. return this;
  24759. };
  24760. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24761. if (!BABYLON.PickingInfo) {
  24762. return null;
  24763. }
  24764. var pickingInfo = null;
  24765. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24766. var mesh = this.meshes[meshIndex];
  24767. if (predicate) {
  24768. if (!predicate(mesh)) {
  24769. continue;
  24770. }
  24771. }
  24772. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24773. continue;
  24774. }
  24775. var world = mesh.getWorldMatrix();
  24776. var ray = rayFunction(world);
  24777. var result = mesh.intersects(ray, fastCheck);
  24778. if (!result || !result.hit)
  24779. continue;
  24780. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24781. continue;
  24782. pickingInfo = result;
  24783. if (fastCheck) {
  24784. break;
  24785. }
  24786. }
  24787. return pickingInfo || new BABYLON.PickingInfo();
  24788. };
  24789. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24790. if (!BABYLON.PickingInfo) {
  24791. return null;
  24792. }
  24793. var pickingInfos = new Array();
  24794. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24795. var mesh = this.meshes[meshIndex];
  24796. if (predicate) {
  24797. if (!predicate(mesh)) {
  24798. continue;
  24799. }
  24800. }
  24801. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24802. continue;
  24803. }
  24804. var world = mesh.getWorldMatrix();
  24805. var ray = rayFunction(world);
  24806. var result = mesh.intersects(ray, false);
  24807. if (!result || !result.hit)
  24808. continue;
  24809. pickingInfos.push(result);
  24810. }
  24811. return pickingInfos;
  24812. };
  24813. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24814. if (!BABYLON.PickingInfo) {
  24815. return null;
  24816. }
  24817. var pickingInfo = null;
  24818. if (!camera) {
  24819. if (!this.activeCamera) {
  24820. return null;
  24821. }
  24822. camera = this.activeCamera;
  24823. }
  24824. if (this.spriteManagers.length > 0) {
  24825. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24826. var spriteManager = this.spriteManagers[spriteIndex];
  24827. if (!spriteManager.isPickable) {
  24828. continue;
  24829. }
  24830. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24831. if (!result || !result.hit)
  24832. continue;
  24833. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24834. continue;
  24835. pickingInfo = result;
  24836. if (fastCheck) {
  24837. break;
  24838. }
  24839. }
  24840. }
  24841. return pickingInfo || new BABYLON.PickingInfo();
  24842. };
  24843. /** Launch a ray to try to pick a mesh in the scene
  24844. * @param x position on screen
  24845. * @param y position on screen
  24846. * @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
  24847. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24848. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24849. */
  24850. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24851. var _this = this;
  24852. if (!BABYLON.PickingInfo) {
  24853. return null;
  24854. }
  24855. return this._internalPick(function (world) {
  24856. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24857. return _this._tempPickingRay;
  24858. }, predicate, fastCheck);
  24859. };
  24860. /** Launch a ray to try to pick a sprite in the scene
  24861. * @param x position on screen
  24862. * @param y position on screen
  24863. * @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
  24864. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24865. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24866. */
  24867. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24868. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24869. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24870. };
  24871. /** Use the given ray to pick a mesh in the scene
  24872. * @param ray The ray to use to pick meshes
  24873. * @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
  24874. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24875. */
  24876. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24877. var _this = this;
  24878. return this._internalPick(function (world) {
  24879. if (!_this._pickWithRayInverseMatrix) {
  24880. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24881. }
  24882. world.invertToRef(_this._pickWithRayInverseMatrix);
  24883. if (!_this._cachedRayForTransform) {
  24884. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24885. }
  24886. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24887. return _this._cachedRayForTransform;
  24888. }, predicate, fastCheck);
  24889. };
  24890. /**
  24891. * Launch a ray to try to pick a mesh in the scene
  24892. * @param x X position on screen
  24893. * @param y Y position on screen
  24894. * @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
  24895. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24896. */
  24897. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24898. var _this = this;
  24899. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24900. };
  24901. /**
  24902. * Launch a ray to try to pick a mesh in the scene
  24903. * @param ray Ray to use
  24904. * @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
  24905. */
  24906. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24907. var _this = this;
  24908. return this._internalMultiPick(function (world) {
  24909. if (!_this._pickWithRayInverseMatrix) {
  24910. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24911. }
  24912. world.invertToRef(_this._pickWithRayInverseMatrix);
  24913. if (!_this._cachedRayForTransform) {
  24914. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24915. }
  24916. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24917. return _this._cachedRayForTransform;
  24918. }, predicate);
  24919. };
  24920. Scene.prototype.setPointerOverMesh = function (mesh) {
  24921. if (this._pointerOverMesh === mesh) {
  24922. return;
  24923. }
  24924. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24925. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24926. }
  24927. this._pointerOverMesh = mesh;
  24928. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24929. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24930. }
  24931. };
  24932. Scene.prototype.getPointerOverMesh = function () {
  24933. return this._pointerOverMesh;
  24934. };
  24935. Scene.prototype.setPointerOverSprite = function (sprite) {
  24936. if (this._pointerOverSprite === sprite) {
  24937. return;
  24938. }
  24939. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24940. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24941. }
  24942. this._pointerOverSprite = sprite;
  24943. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24944. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24945. }
  24946. };
  24947. Scene.prototype.getPointerOverSprite = function () {
  24948. return this._pointerOverSprite;
  24949. };
  24950. // Physics
  24951. Scene.prototype.getPhysicsEngine = function () {
  24952. return this._physicsEngine;
  24953. };
  24954. /**
  24955. * Enables physics to the current scene
  24956. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24957. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24958. * @return {boolean} was the physics engine initialized
  24959. */
  24960. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24961. if (gravity === void 0) { gravity = null; }
  24962. if (this._physicsEngine) {
  24963. return true;
  24964. }
  24965. try {
  24966. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24967. return true;
  24968. }
  24969. catch (e) {
  24970. BABYLON.Tools.Error(e.message);
  24971. return false;
  24972. }
  24973. };
  24974. Scene.prototype.disablePhysicsEngine = function () {
  24975. if (!this._physicsEngine) {
  24976. return;
  24977. }
  24978. this._physicsEngine.dispose();
  24979. this._physicsEngine = null;
  24980. };
  24981. Scene.prototype.isPhysicsEnabled = function () {
  24982. return this._physicsEngine !== undefined;
  24983. };
  24984. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24985. var mesh = compound.parts[0].mesh;
  24986. if (mesh.physicsImpostor) {
  24987. mesh.physicsImpostor.dispose();
  24988. mesh.physicsImpostor = null;
  24989. }
  24990. };
  24991. // Misc.
  24992. Scene.prototype._rebuildGeometries = function () {
  24993. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24994. var geometry = _a[_i];
  24995. geometry._rebuild();
  24996. }
  24997. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24998. var mesh = _c[_b];
  24999. mesh._rebuild();
  25000. }
  25001. if (this.postProcessManager) {
  25002. this.postProcessManager._rebuild();
  25003. }
  25004. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25005. var layer = _e[_d];
  25006. layer._rebuild();
  25007. }
  25008. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25009. var effectLayer = _g[_f];
  25010. effectLayer._rebuild();
  25011. }
  25012. if (this._boundingBoxRenderer) {
  25013. this._boundingBoxRenderer._rebuild();
  25014. }
  25015. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25016. var system = _j[_h];
  25017. system.rebuild();
  25018. }
  25019. if (this._postProcessRenderPipelineManager) {
  25020. this._postProcessRenderPipelineManager._rebuild();
  25021. }
  25022. };
  25023. Scene.prototype._rebuildTextures = function () {
  25024. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25025. var texture = _a[_i];
  25026. texture._rebuild();
  25027. }
  25028. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25029. };
  25030. /**
  25031. * Creates a default light for the scene.
  25032. * @param replace Whether to replace the existing lights in the scene.
  25033. */
  25034. Scene.prototype.createDefaultLight = function (replace) {
  25035. if (replace === void 0) { replace = false; }
  25036. // Dispose existing light in replace mode.
  25037. if (replace) {
  25038. if (this.lights) {
  25039. for (var i = 0; i < this.lights.length; i++) {
  25040. this.lights[i].dispose();
  25041. }
  25042. }
  25043. }
  25044. // Light
  25045. if (this.lights.length === 0) {
  25046. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25047. }
  25048. };
  25049. /**
  25050. * Creates a default camera for the scene.
  25051. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25052. * @param replace Whether to replace the existing active camera in the scene.
  25053. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25054. */
  25055. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25056. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25057. if (replace === void 0) { replace = false; }
  25058. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25059. // Dispose existing camera in replace mode.
  25060. if (replace) {
  25061. if (this.activeCamera) {
  25062. this.activeCamera.dispose();
  25063. this.activeCamera = null;
  25064. }
  25065. }
  25066. // Camera
  25067. if (!this.activeCamera) {
  25068. var worldExtends = this.getWorldExtends();
  25069. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25070. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25071. var camera;
  25072. var radius = worldSize.length() * 1.5;
  25073. // empty scene scenario!
  25074. if (!isFinite(radius)) {
  25075. radius = 1;
  25076. worldCenter.copyFromFloats(0, 0, 0);
  25077. }
  25078. if (createArcRotateCamera) {
  25079. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25080. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25081. arcRotateCamera.wheelPrecision = 100 / radius;
  25082. camera = arcRotateCamera;
  25083. }
  25084. else {
  25085. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25086. freeCamera.setTarget(worldCenter);
  25087. camera = freeCamera;
  25088. }
  25089. camera.minZ = radius * 0.01;
  25090. camera.maxZ = radius * 1000;
  25091. camera.speed = radius * 0.2;
  25092. this.activeCamera = camera;
  25093. var canvas = this.getEngine().getRenderingCanvas();
  25094. if (attachCameraControls && canvas) {
  25095. camera.attachControl(canvas);
  25096. }
  25097. }
  25098. };
  25099. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25100. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25101. if (replace === void 0) { replace = false; }
  25102. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25103. this.createDefaultLight(replace);
  25104. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25105. };
  25106. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25107. if (pbr === void 0) { pbr = false; }
  25108. if (scale === void 0) { scale = 1000; }
  25109. if (blur === void 0) { blur = 0; }
  25110. if (environmentTexture) {
  25111. this.environmentTexture = environmentTexture;
  25112. }
  25113. if (!this.environmentTexture) {
  25114. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25115. return null;
  25116. }
  25117. // Skybox
  25118. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25119. if (pbr) {
  25120. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25121. hdrSkyboxMaterial.backFaceCulling = false;
  25122. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25123. if (hdrSkyboxMaterial.reflectionTexture) {
  25124. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25125. }
  25126. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25127. hdrSkyboxMaterial.disableLighting = true;
  25128. hdrSkyboxMaterial.twoSidedLighting = true;
  25129. hdrSkybox.infiniteDistance = true;
  25130. hdrSkybox.material = hdrSkyboxMaterial;
  25131. }
  25132. else {
  25133. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25134. skyboxMaterial.backFaceCulling = false;
  25135. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25136. if (skyboxMaterial.reflectionTexture) {
  25137. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25138. }
  25139. skyboxMaterial.disableLighting = true;
  25140. hdrSkybox.infiniteDistance = true;
  25141. hdrSkybox.material = skyboxMaterial;
  25142. }
  25143. return hdrSkybox;
  25144. };
  25145. Scene.prototype.createDefaultEnvironment = function (options) {
  25146. if (BABYLON.EnvironmentHelper) {
  25147. return new BABYLON.EnvironmentHelper(options, this);
  25148. }
  25149. return null;
  25150. };
  25151. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25152. if (webVROptions === void 0) { webVROptions = {}; }
  25153. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25154. };
  25155. // Tags
  25156. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25157. if (tagsQuery === undefined) {
  25158. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25159. return list;
  25160. }
  25161. var listByTags = [];
  25162. forEach = forEach || (function (item) { return; });
  25163. for (var i in list) {
  25164. var item = list[i];
  25165. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25166. listByTags.push(item);
  25167. forEach(item);
  25168. }
  25169. }
  25170. return listByTags;
  25171. };
  25172. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25173. return this._getByTags(this.meshes, tagsQuery, forEach);
  25174. };
  25175. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25176. return this._getByTags(this.cameras, tagsQuery, forEach);
  25177. };
  25178. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25179. return this._getByTags(this.lights, tagsQuery, forEach);
  25180. };
  25181. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25182. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25183. };
  25184. /**
  25185. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25186. * This allowed control for front to back rendering or reversly depending of the special needs.
  25187. *
  25188. * @param renderingGroupId The rendering group id corresponding to its index
  25189. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25190. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25191. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25192. */
  25193. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25194. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25195. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25196. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25197. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25198. };
  25199. /**
  25200. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25201. *
  25202. * @param renderingGroupId The rendering group id corresponding to its index
  25203. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25204. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25205. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25206. */
  25207. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25208. if (depth === void 0) { depth = true; }
  25209. if (stencil === void 0) { stencil = true; }
  25210. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25211. };
  25212. /**
  25213. * Will flag all materials as dirty to trigger new shader compilation
  25214. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25215. */
  25216. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25217. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25218. var material = _a[_i];
  25219. if (predicate && !predicate(material)) {
  25220. continue;
  25221. }
  25222. material.markAsDirty(flag);
  25223. }
  25224. };
  25225. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25226. var _this = this;
  25227. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25228. this._activeRequests.push(request);
  25229. request.onCompleteObservable.add(function (request) {
  25230. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25231. });
  25232. return request;
  25233. };
  25234. /** @ignore */
  25235. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25236. var _this = this;
  25237. return new Promise(function (resolve, reject) {
  25238. _this._loadFile(url, function (data) {
  25239. resolve(data);
  25240. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25241. reject(exception);
  25242. });
  25243. });
  25244. };
  25245. // Statics
  25246. Scene._FOGMODE_NONE = 0;
  25247. Scene._FOGMODE_EXP = 1;
  25248. Scene._FOGMODE_EXP2 = 2;
  25249. Scene._FOGMODE_LINEAR = 3;
  25250. Scene._uniqueIdCounter = 0;
  25251. Scene.MinDeltaTime = 1.0;
  25252. Scene.MaxDeltaTime = 1000.0;
  25253. /** The distance in pixel that you have to move to prevent some events */
  25254. Scene.DragMovementThreshold = 10; // in pixels
  25255. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25256. Scene.LongPressDelay = 500; // in milliseconds
  25257. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25258. Scene.DoubleClickDelay = 300; // in milliseconds
  25259. /** If you need to check double click without raising a single click at first click, enable this flag */
  25260. Scene.ExclusiveDoubleClickMode = false;
  25261. return Scene;
  25262. }());
  25263. BABYLON.Scene = Scene;
  25264. })(BABYLON || (BABYLON = {}));
  25265. //# sourceMappingURL=babylon.scene.js.map
  25266. var BABYLON;
  25267. (function (BABYLON) {
  25268. /**
  25269. * Set of assets to keep when moving a scene into an asset container.
  25270. */
  25271. var KeepAssets = /** @class */ (function () {
  25272. function KeepAssets() {
  25273. /**
  25274. * Cameras to keep.
  25275. */
  25276. this.cameras = new Array();
  25277. /**
  25278. * Lights to keep.
  25279. */
  25280. this.lights = new Array();
  25281. /**
  25282. * Meshes to keep.
  25283. */
  25284. this.meshes = new Array();
  25285. /**
  25286. * Skeletons to keep.
  25287. */
  25288. this.skeletons = new Array();
  25289. /**
  25290. * ParticleSystems to keep.
  25291. */
  25292. this.particleSystems = new Array();
  25293. /**
  25294. * Animations to keep.
  25295. */
  25296. this.animations = new Array();
  25297. /**
  25298. * MultiMaterials to keep.
  25299. */
  25300. this.multiMaterials = new Array();
  25301. /**
  25302. * Materials to keep.
  25303. */
  25304. this.materials = new Array();
  25305. /**
  25306. * MorphTargetManagers to keep.
  25307. */
  25308. this.morphTargetManagers = new Array();
  25309. /**
  25310. * Geometries to keep.
  25311. */
  25312. this.geometries = new Array();
  25313. /**
  25314. * TransformNodes to keep.
  25315. */
  25316. this.transformNodes = new Array();
  25317. /**
  25318. * LensFlareSystems to keep.
  25319. */
  25320. this.lensFlareSystems = new Array();
  25321. /**
  25322. * ShadowGenerators to keep.
  25323. */
  25324. this.shadowGenerators = new Array();
  25325. /**
  25326. * ActionManagers to keep.
  25327. */
  25328. this.actionManagers = new Array();
  25329. /**
  25330. * Sounds to keep.
  25331. */
  25332. this.sounds = new Array();
  25333. }
  25334. return KeepAssets;
  25335. }());
  25336. BABYLON.KeepAssets = KeepAssets;
  25337. /**
  25338. * Container with a set of assets that can be added or removed from a scene.
  25339. */
  25340. var AssetContainer = /** @class */ (function () {
  25341. /**
  25342. * Instantiates an AssetContainer.
  25343. * @param scene The scene the AssetContainer belongs to.
  25344. */
  25345. function AssetContainer(scene) {
  25346. // Objects
  25347. /**
  25348. * Cameras populated in the container.
  25349. */
  25350. this.cameras = new Array();
  25351. /**
  25352. * Lights populated in the container.
  25353. */
  25354. this.lights = new Array();
  25355. /**
  25356. * Meshes populated in the container.
  25357. */
  25358. this.meshes = new Array();
  25359. /**
  25360. * Skeletons populated in the container.
  25361. */
  25362. this.skeletons = new Array();
  25363. /**
  25364. * ParticleSystems populated in the container.
  25365. */
  25366. this.particleSystems = new Array();
  25367. /**
  25368. * Animations populated in the container.
  25369. */
  25370. this.animations = new Array();
  25371. /**
  25372. * MultiMaterials populated in the container.
  25373. */
  25374. this.multiMaterials = new Array();
  25375. /**
  25376. * Materials populated in the container.
  25377. */
  25378. this.materials = new Array();
  25379. /**
  25380. * MorphTargetManagers populated in the container.
  25381. */
  25382. this.morphTargetManagers = new Array();
  25383. /**
  25384. * Geometries populated in the container.
  25385. */
  25386. this.geometries = new Array();
  25387. /**
  25388. * TransformNodes populated in the container.
  25389. */
  25390. this.transformNodes = new Array();
  25391. /**
  25392. * LensFlareSystems populated in the container.
  25393. */
  25394. this.lensFlareSystems = new Array();
  25395. /**
  25396. * ShadowGenerators populated in the container.
  25397. */
  25398. this.shadowGenerators = new Array();
  25399. /**
  25400. * ActionManagers populated in the container.
  25401. */
  25402. this.actionManagers = new Array();
  25403. /**
  25404. * Sounds populated in the container.
  25405. */
  25406. this.sounds = new Array();
  25407. this.scene = scene;
  25408. }
  25409. /**
  25410. * Adds all the assets from the container to the scene.
  25411. */
  25412. AssetContainer.prototype.addAllToScene = function () {
  25413. var _this = this;
  25414. this.cameras.forEach(function (o) {
  25415. _this.scene.addCamera(o);
  25416. });
  25417. this.lights.forEach(function (o) {
  25418. _this.scene.addLight(o);
  25419. });
  25420. this.meshes.forEach(function (o) {
  25421. _this.scene.addMesh(o);
  25422. });
  25423. this.skeletons.forEach(function (o) {
  25424. _this.scene.addSkeleton(o);
  25425. });
  25426. this.particleSystems.forEach(function (o) {
  25427. _this.scene.addParticleSystem(o);
  25428. });
  25429. this.animations.forEach(function (o) {
  25430. _this.scene.addAnimation(o);
  25431. });
  25432. this.multiMaterials.forEach(function (o) {
  25433. _this.scene.addMultiMaterial(o);
  25434. });
  25435. this.materials.forEach(function (o) {
  25436. _this.scene.addMaterial(o);
  25437. });
  25438. this.morphTargetManagers.forEach(function (o) {
  25439. _this.scene.addMorphTargetManager(o);
  25440. });
  25441. this.geometries.forEach(function (o) {
  25442. _this.scene.addGeometry(o);
  25443. });
  25444. this.transformNodes.forEach(function (o) {
  25445. _this.scene.addTransformNode(o);
  25446. });
  25447. this.lensFlareSystems.forEach(function (o) {
  25448. _this.scene.addLensFlareSystem(o);
  25449. });
  25450. this.actionManagers.forEach(function (o) {
  25451. _this.scene.addActionManager(o);
  25452. });
  25453. this.sounds.forEach(function (o) {
  25454. o.play();
  25455. o.autoplay = true;
  25456. _this.scene.mainSoundTrack.AddSound(o);
  25457. });
  25458. };
  25459. /**
  25460. * Removes all the assets in the container from the scene
  25461. */
  25462. AssetContainer.prototype.removeAllFromScene = function () {
  25463. var _this = this;
  25464. this.cameras.forEach(function (o) {
  25465. _this.scene.removeCamera(o);
  25466. });
  25467. this.lights.forEach(function (o) {
  25468. _this.scene.removeLight(o);
  25469. });
  25470. this.meshes.forEach(function (o) {
  25471. _this.scene.removeMesh(o);
  25472. });
  25473. this.skeletons.forEach(function (o) {
  25474. _this.scene.removeSkeleton(o);
  25475. });
  25476. this.particleSystems.forEach(function (o) {
  25477. _this.scene.removeParticleSystem(o);
  25478. });
  25479. this.animations.forEach(function (o) {
  25480. _this.scene.removeAnimation(o);
  25481. });
  25482. this.multiMaterials.forEach(function (o) {
  25483. _this.scene.removeMultiMaterial(o);
  25484. });
  25485. this.materials.forEach(function (o) {
  25486. _this.scene.removeMaterial(o);
  25487. });
  25488. this.morphTargetManagers.forEach(function (o) {
  25489. _this.scene.removeMorphTargetManager(o);
  25490. });
  25491. this.geometries.forEach(function (o) {
  25492. _this.scene.removeGeometry(o);
  25493. });
  25494. this.transformNodes.forEach(function (o) {
  25495. _this.scene.removeTransformNode(o);
  25496. });
  25497. this.lensFlareSystems.forEach(function (o) {
  25498. _this.scene.removeLensFlareSystem(o);
  25499. });
  25500. this.actionManagers.forEach(function (o) {
  25501. _this.scene.removeActionManager(o);
  25502. });
  25503. this.sounds.forEach(function (o) {
  25504. o.stop();
  25505. o.autoplay = false;
  25506. _this.scene.mainSoundTrack.RemoveSound(o);
  25507. });
  25508. };
  25509. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25510. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25511. var asset = sourceAssets_1[_i];
  25512. var move = true;
  25513. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25514. var keepAsset = keepAssets_1[_a];
  25515. if (asset === keepAsset) {
  25516. move = false;
  25517. break;
  25518. }
  25519. }
  25520. if (move) {
  25521. targetAssets.push(asset);
  25522. }
  25523. }
  25524. };
  25525. /**
  25526. * Removes all the assets contained in the scene and adds them to the container.
  25527. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25528. */
  25529. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25530. if (keepAssets === undefined) {
  25531. keepAssets = new KeepAssets();
  25532. }
  25533. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25534. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25535. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25536. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25537. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25538. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25539. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25540. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25541. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25542. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25543. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25544. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25545. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25546. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25547. this.removeAllFromScene();
  25548. };
  25549. return AssetContainer;
  25550. }());
  25551. BABYLON.AssetContainer = AssetContainer;
  25552. })(BABYLON || (BABYLON = {}));
  25553. //# sourceMappingURL=babylon.assetContainer.js.map
  25554. var BABYLON;
  25555. (function (BABYLON) {
  25556. var Buffer = /** @class */ (function () {
  25557. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25558. if (instanced === void 0) { instanced = false; }
  25559. if (engine instanceof BABYLON.Mesh) {
  25560. this._engine = engine.getScene().getEngine();
  25561. }
  25562. else {
  25563. this._engine = engine;
  25564. }
  25565. this._updatable = updatable;
  25566. this._instanced = instanced;
  25567. this._data = data;
  25568. this._strideSize = stride;
  25569. if (!postponeInternalCreation) {
  25570. this.create();
  25571. }
  25572. }
  25573. /**
  25574. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25575. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25576. * @param offset defines offset in the buffer (0 by default)
  25577. * @param size defines the size in floats of attributes (position is 3 for instance)
  25578. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25579. * @param instanced defines if the vertex buffer contains indexed data
  25580. * @returns the new vertex buffer
  25581. */
  25582. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25583. // a lot of these parameters are ignored as they are overriden by the buffer
  25584. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25585. };
  25586. // Properties
  25587. Buffer.prototype.isUpdatable = function () {
  25588. return this._updatable;
  25589. };
  25590. Buffer.prototype.getData = function () {
  25591. return this._data;
  25592. };
  25593. Buffer.prototype.getBuffer = function () {
  25594. return this._buffer;
  25595. };
  25596. Buffer.prototype.getStrideSize = function () {
  25597. return this._strideSize;
  25598. };
  25599. // public getIsInstanced(): boolean {
  25600. // return this._instanced;
  25601. // }
  25602. // public get instanceDivisor(): number {
  25603. // return this._instanceDivisor;
  25604. // }
  25605. // public set instanceDivisor(value: number) {
  25606. // this._instanceDivisor = value;
  25607. // if (value == 0) {
  25608. // this._instanced = false;
  25609. // } else {
  25610. // this._instanced = true;
  25611. // }
  25612. // }
  25613. // Methods
  25614. Buffer.prototype.create = function (data) {
  25615. if (data === void 0) { data = null; }
  25616. if (!data && this._buffer) {
  25617. return; // nothing to do
  25618. }
  25619. data = data || this._data;
  25620. if (!data) {
  25621. return;
  25622. }
  25623. if (!this._buffer) {
  25624. if (this._updatable) {
  25625. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25626. this._data = data;
  25627. }
  25628. else {
  25629. this._buffer = this._engine.createVertexBuffer(data);
  25630. }
  25631. }
  25632. else if (this._updatable) {
  25633. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25634. this._data = data;
  25635. }
  25636. };
  25637. Buffer.prototype._rebuild = function () {
  25638. this._buffer = null;
  25639. this.create(this._data);
  25640. };
  25641. Buffer.prototype.update = function (data) {
  25642. this.create(data);
  25643. };
  25644. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25645. if (!this._buffer) {
  25646. return;
  25647. }
  25648. if (this._updatable) {
  25649. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25650. this._data = null;
  25651. }
  25652. };
  25653. Buffer.prototype.dispose = function () {
  25654. if (!this._buffer) {
  25655. return;
  25656. }
  25657. if (this._engine._releaseBuffer(this._buffer)) {
  25658. this._buffer = null;
  25659. }
  25660. };
  25661. return Buffer;
  25662. }());
  25663. BABYLON.Buffer = Buffer;
  25664. })(BABYLON || (BABYLON = {}));
  25665. //# sourceMappingURL=babylon.buffer.js.map
  25666. var BABYLON;
  25667. (function (BABYLON) {
  25668. var VertexBuffer = /** @class */ (function () {
  25669. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25670. if (data instanceof BABYLON.Buffer) {
  25671. if (!stride) {
  25672. stride = data.getStrideSize();
  25673. }
  25674. this._buffer = data;
  25675. this._ownsBuffer = false;
  25676. }
  25677. else {
  25678. if (!stride) {
  25679. stride = VertexBuffer.DeduceStride(kind);
  25680. }
  25681. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25682. this._ownsBuffer = true;
  25683. }
  25684. this._stride = stride;
  25685. this._instanced = instanced !== undefined ? instanced : false;
  25686. this._instanceDivisor = instanced ? 1 : 0;
  25687. this._offset = offset ? offset : 0;
  25688. this._size = size ? size : stride;
  25689. this._kind = kind;
  25690. }
  25691. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25692. /**
  25693. * Gets or sets the instance divisor when in instanced mode
  25694. */
  25695. get: function () {
  25696. return this._instanceDivisor;
  25697. },
  25698. set: function (value) {
  25699. this._instanceDivisor = value;
  25700. if (value == 0) {
  25701. this._instanced = false;
  25702. }
  25703. else {
  25704. this._instanced = true;
  25705. }
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. VertexBuffer.prototype._rebuild = function () {
  25711. if (!this._buffer) {
  25712. return;
  25713. }
  25714. this._buffer._rebuild();
  25715. };
  25716. /**
  25717. * Returns the kind of the VertexBuffer (string).
  25718. */
  25719. VertexBuffer.prototype.getKind = function () {
  25720. return this._kind;
  25721. };
  25722. // Properties
  25723. /**
  25724. * Boolean : is the VertexBuffer updatable ?
  25725. */
  25726. VertexBuffer.prototype.isUpdatable = function () {
  25727. return this._buffer.isUpdatable();
  25728. };
  25729. /**
  25730. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25731. */
  25732. VertexBuffer.prototype.getData = function () {
  25733. return this._buffer.getData();
  25734. };
  25735. /**
  25736. * Returns the WebGLBuffer associated to the VertexBuffer.
  25737. */
  25738. VertexBuffer.prototype.getBuffer = function () {
  25739. return this._buffer.getBuffer();
  25740. };
  25741. /**
  25742. * Returns the stride of the VertexBuffer (integer).
  25743. */
  25744. VertexBuffer.prototype.getStrideSize = function () {
  25745. return this._stride;
  25746. };
  25747. /**
  25748. * Returns the offset (integer).
  25749. */
  25750. VertexBuffer.prototype.getOffset = function () {
  25751. return this._offset;
  25752. };
  25753. /**
  25754. * Returns the VertexBuffer total size (integer).
  25755. */
  25756. VertexBuffer.prototype.getSize = function () {
  25757. return this._size;
  25758. };
  25759. /**
  25760. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25761. */
  25762. VertexBuffer.prototype.getIsInstanced = function () {
  25763. return this._instanced;
  25764. };
  25765. /**
  25766. * Returns the instancing divisor, zero for non-instanced (integer).
  25767. */
  25768. VertexBuffer.prototype.getInstanceDivisor = function () {
  25769. return this._instanceDivisor;
  25770. };
  25771. // Methods
  25772. /**
  25773. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25774. * Returns the created WebGLBuffer.
  25775. */
  25776. VertexBuffer.prototype.create = function (data) {
  25777. return this._buffer.create(data);
  25778. };
  25779. /**
  25780. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25781. * This function will create a new buffer if the current one is not updatable
  25782. * Returns the updated WebGLBuffer.
  25783. */
  25784. VertexBuffer.prototype.update = function (data) {
  25785. return this._buffer.update(data);
  25786. };
  25787. /**
  25788. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25789. * Returns the directly updated WebGLBuffer.
  25790. */
  25791. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25792. return this._buffer.updateDirectly(data, offset);
  25793. };
  25794. /**
  25795. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25796. */
  25797. VertexBuffer.prototype.dispose = function () {
  25798. if (this._ownsBuffer) {
  25799. this._buffer.dispose();
  25800. }
  25801. };
  25802. Object.defineProperty(VertexBuffer, "PositionKind", {
  25803. get: function () {
  25804. return VertexBuffer._PositionKind;
  25805. },
  25806. enumerable: true,
  25807. configurable: true
  25808. });
  25809. Object.defineProperty(VertexBuffer, "NormalKind", {
  25810. get: function () {
  25811. return VertexBuffer._NormalKind;
  25812. },
  25813. enumerable: true,
  25814. configurable: true
  25815. });
  25816. Object.defineProperty(VertexBuffer, "TangentKind", {
  25817. get: function () {
  25818. return VertexBuffer._TangentKind;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. Object.defineProperty(VertexBuffer, "UVKind", {
  25824. get: function () {
  25825. return VertexBuffer._UVKind;
  25826. },
  25827. enumerable: true,
  25828. configurable: true
  25829. });
  25830. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25831. get: function () {
  25832. return VertexBuffer._UV2Kind;
  25833. },
  25834. enumerable: true,
  25835. configurable: true
  25836. });
  25837. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25838. get: function () {
  25839. return VertexBuffer._UV3Kind;
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25845. get: function () {
  25846. return VertexBuffer._UV4Kind;
  25847. },
  25848. enumerable: true,
  25849. configurable: true
  25850. });
  25851. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25852. get: function () {
  25853. return VertexBuffer._UV5Kind;
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25859. get: function () {
  25860. return VertexBuffer._UV6Kind;
  25861. },
  25862. enumerable: true,
  25863. configurable: true
  25864. });
  25865. Object.defineProperty(VertexBuffer, "ColorKind", {
  25866. get: function () {
  25867. return VertexBuffer._ColorKind;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25873. get: function () {
  25874. return VertexBuffer._MatricesIndicesKind;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25880. get: function () {
  25881. return VertexBuffer._MatricesWeightsKind;
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25887. get: function () {
  25888. return VertexBuffer._MatricesIndicesExtraKind;
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25894. get: function () {
  25895. return VertexBuffer._MatricesWeightsExtraKind;
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. /**
  25901. * Deduces the stride given a kind.
  25902. * @param kind The kind string to deduce
  25903. * @returns The deduced stride
  25904. */
  25905. VertexBuffer.DeduceStride = function (kind) {
  25906. switch (kind) {
  25907. case VertexBuffer.UVKind:
  25908. case VertexBuffer.UV2Kind:
  25909. case VertexBuffer.UV3Kind:
  25910. case VertexBuffer.UV4Kind:
  25911. case VertexBuffer.UV5Kind:
  25912. case VertexBuffer.UV6Kind:
  25913. return 2;
  25914. case VertexBuffer.NormalKind:
  25915. case VertexBuffer.PositionKind:
  25916. return 3;
  25917. case VertexBuffer.ColorKind:
  25918. case VertexBuffer.MatricesIndicesKind:
  25919. case VertexBuffer.MatricesIndicesExtraKind:
  25920. case VertexBuffer.MatricesWeightsKind:
  25921. case VertexBuffer.MatricesWeightsExtraKind:
  25922. case VertexBuffer.TangentKind:
  25923. return 4;
  25924. default:
  25925. throw new Error("Invalid kind '" + kind + "'");
  25926. }
  25927. };
  25928. // Enums
  25929. VertexBuffer._PositionKind = "position";
  25930. VertexBuffer._NormalKind = "normal";
  25931. VertexBuffer._TangentKind = "tangent";
  25932. VertexBuffer._UVKind = "uv";
  25933. VertexBuffer._UV2Kind = "uv2";
  25934. VertexBuffer._UV3Kind = "uv3";
  25935. VertexBuffer._UV4Kind = "uv4";
  25936. VertexBuffer._UV5Kind = "uv5";
  25937. VertexBuffer._UV6Kind = "uv6";
  25938. VertexBuffer._ColorKind = "color";
  25939. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25940. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25941. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25942. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25943. return VertexBuffer;
  25944. }());
  25945. BABYLON.VertexBuffer = VertexBuffer;
  25946. })(BABYLON || (BABYLON = {}));
  25947. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25948. var BABYLON;
  25949. (function (BABYLON) {
  25950. /**
  25951. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25952. */
  25953. var DummyInternalTextureTracker = /** @class */ (function () {
  25954. function DummyInternalTextureTracker() {
  25955. /**
  25956. * Gets or set the previous tracker in the list
  25957. */
  25958. this.previous = null;
  25959. /**
  25960. * Gets or set the next tracker in the list
  25961. */
  25962. this.next = null;
  25963. }
  25964. return DummyInternalTextureTracker;
  25965. }());
  25966. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25967. })(BABYLON || (BABYLON = {}));
  25968. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25969. var BABYLON;
  25970. (function (BABYLON) {
  25971. /**
  25972. * Class used to store data associated with WebGL texture data for the engine
  25973. * This class should not be used directly
  25974. */
  25975. var InternalTexture = /** @class */ (function () {
  25976. /**
  25977. * Creates a new InternalTexture
  25978. * @param engine defines the engine to use
  25979. * @param dataSource defines the type of data that will be used
  25980. */
  25981. function InternalTexture(engine, dataSource) {
  25982. /**
  25983. * Observable called when the texture is loaded
  25984. */
  25985. this.onLoadedObservable = new BABYLON.Observable();
  25986. /**
  25987. * Gets or set the previous tracker in the list
  25988. */
  25989. this.previous = null;
  25990. /**
  25991. * Gets or set the next tracker in the list
  25992. */
  25993. this.next = null;
  25994. // Private
  25995. /** @ignore */
  25996. this._initialSlot = -1;
  25997. /** @ignore */
  25998. this._designatedSlot = -1;
  25999. /** @ignore */
  26000. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26001. /** @ignore */
  26002. this._comparisonFunction = 0;
  26003. /** @ignore */
  26004. this._references = 1;
  26005. this._engine = engine;
  26006. this._dataSource = dataSource;
  26007. this._webGLTexture = engine._createTexture();
  26008. }
  26009. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26010. /**
  26011. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26012. */
  26013. get: function () {
  26014. return this._dataSource;
  26015. },
  26016. enumerable: true,
  26017. configurable: true
  26018. });
  26019. /**
  26020. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26021. */
  26022. InternalTexture.prototype.incrementReferences = function () {
  26023. this._references++;
  26024. };
  26025. /**
  26026. * Change the size of the texture (not the size of the content)
  26027. * @param width defines the new width
  26028. * @param height defines the new height
  26029. * @param depth defines the new depth (1 by default)
  26030. */
  26031. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26032. if (depth === void 0) { depth = 1; }
  26033. this.width = width;
  26034. this.height = height;
  26035. this.depth = depth;
  26036. this.baseWidth = width;
  26037. this.baseHeight = height;
  26038. this.baseDepth = depth;
  26039. this._size = width * height * depth;
  26040. };
  26041. /** @ignore */
  26042. InternalTexture.prototype._rebuild = function () {
  26043. var _this = this;
  26044. var proxy;
  26045. this.isReady = false;
  26046. this._cachedCoordinatesMode = null;
  26047. this._cachedWrapU = null;
  26048. this._cachedWrapV = null;
  26049. this._cachedAnisotropicFilteringLevel = null;
  26050. switch (this._dataSource) {
  26051. case InternalTexture.DATASOURCE_TEMP:
  26052. return;
  26053. case InternalTexture.DATASOURCE_URL:
  26054. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26055. _this.isReady = true;
  26056. }, null, this._buffer, undefined, this.format);
  26057. proxy._swapAndDie(this);
  26058. return;
  26059. case InternalTexture.DATASOURCE_RAW:
  26060. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26061. proxy._swapAndDie(this);
  26062. this.isReady = true;
  26063. return;
  26064. case InternalTexture.DATASOURCE_RAW3D:
  26065. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26066. proxy._swapAndDie(this);
  26067. this.isReady = true;
  26068. return;
  26069. case InternalTexture.DATASOURCE_DYNAMIC:
  26070. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26071. proxy._swapAndDie(this);
  26072. // The engine will make sure to update content so no need to flag it as isReady = true
  26073. return;
  26074. case InternalTexture.DATASOURCE_RENDERTARGET:
  26075. var options = new BABYLON.RenderTargetCreationOptions();
  26076. options.generateDepthBuffer = this._generateDepthBuffer;
  26077. options.generateMipMaps = this.generateMipMaps;
  26078. options.generateStencilBuffer = this._generateStencilBuffer;
  26079. options.samplingMode = this.samplingMode;
  26080. options.type = this.type;
  26081. if (this.isCube) {
  26082. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26083. }
  26084. else {
  26085. var size = {
  26086. width: this.width,
  26087. height: this.height
  26088. };
  26089. proxy = this._engine.createRenderTargetTexture(size, options);
  26090. }
  26091. proxy._swapAndDie(this);
  26092. this.isReady = true;
  26093. return;
  26094. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26095. var depthTextureOptions = {
  26096. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26097. comparisonFunction: this._comparisonFunction,
  26098. generateStencil: this._generateStencilBuffer,
  26099. };
  26100. if (this.isCube) {
  26101. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26102. }
  26103. else {
  26104. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26105. }
  26106. proxy._swapAndDie(this);
  26107. this.isReady = true;
  26108. return;
  26109. case InternalTexture.DATASOURCE_CUBE:
  26110. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26111. _this.isReady = true;
  26112. }, null, this.format, this._extension);
  26113. proxy._swapAndDie(this);
  26114. return;
  26115. case InternalTexture.DATASOURCE_CUBERAW:
  26116. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26117. proxy._swapAndDie(this);
  26118. this.isReady = true;
  26119. return;
  26120. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26121. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26122. if (proxy) {
  26123. proxy._swapAndDie(_this);
  26124. }
  26125. _this.isReady = true;
  26126. }, null, this.format, this._extension);
  26127. return;
  26128. }
  26129. };
  26130. InternalTexture.prototype._swapAndDie = function (target) {
  26131. target._webGLTexture = this._webGLTexture;
  26132. if (this._framebuffer) {
  26133. target._framebuffer = this._framebuffer;
  26134. }
  26135. if (this._depthStencilBuffer) {
  26136. target._depthStencilBuffer = this._depthStencilBuffer;
  26137. }
  26138. if (this._lodTextureHigh) {
  26139. if (target._lodTextureHigh) {
  26140. target._lodTextureHigh.dispose();
  26141. }
  26142. target._lodTextureHigh = this._lodTextureHigh;
  26143. }
  26144. if (this._lodTextureMid) {
  26145. if (target._lodTextureMid) {
  26146. target._lodTextureMid.dispose();
  26147. }
  26148. target._lodTextureMid = this._lodTextureMid;
  26149. }
  26150. if (this._lodTextureLow) {
  26151. if (target._lodTextureLow) {
  26152. target._lodTextureLow.dispose();
  26153. }
  26154. target._lodTextureLow = this._lodTextureLow;
  26155. }
  26156. var cache = this._engine.getLoadedTexturesCache();
  26157. var index = cache.indexOf(this);
  26158. if (index !== -1) {
  26159. cache.splice(index, 1);
  26160. }
  26161. };
  26162. /**
  26163. * Dispose the current allocated resources
  26164. */
  26165. InternalTexture.prototype.dispose = function () {
  26166. if (!this._webGLTexture) {
  26167. return;
  26168. }
  26169. this._references--;
  26170. if (this._references === 0) {
  26171. this._engine._releaseTexture(this);
  26172. this._webGLTexture = null;
  26173. this.previous = null;
  26174. this.next = null;
  26175. }
  26176. };
  26177. /**
  26178. * The source of the texture data is unknown
  26179. */
  26180. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26181. /**
  26182. * Texture data comes from an URL
  26183. */
  26184. InternalTexture.DATASOURCE_URL = 1;
  26185. /**
  26186. * Texture data is only used for temporary storage
  26187. */
  26188. InternalTexture.DATASOURCE_TEMP = 2;
  26189. /**
  26190. * Texture data comes from raw data (ArrayBuffer)
  26191. */
  26192. InternalTexture.DATASOURCE_RAW = 3;
  26193. /**
  26194. * Texture content is dynamic (video or dynamic texture)
  26195. */
  26196. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26197. /**
  26198. * Texture content is generated by rendering to it
  26199. */
  26200. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26201. /**
  26202. * Texture content is part of a multi render target process
  26203. */
  26204. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26205. /**
  26206. * Texture data comes from a cube data file
  26207. */
  26208. InternalTexture.DATASOURCE_CUBE = 7;
  26209. /**
  26210. * Texture data comes from a raw cube data
  26211. */
  26212. InternalTexture.DATASOURCE_CUBERAW = 8;
  26213. /**
  26214. * Texture data come from a prefiltered cube data file
  26215. */
  26216. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26217. /**
  26218. * Texture content is raw 3D data
  26219. */
  26220. InternalTexture.DATASOURCE_RAW3D = 10;
  26221. /**
  26222. * Texture content is a depth texture
  26223. */
  26224. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26225. return InternalTexture;
  26226. }());
  26227. BABYLON.InternalTexture = InternalTexture;
  26228. })(BABYLON || (BABYLON = {}));
  26229. //# sourceMappingURL=babylon.internalTexture.js.map
  26230. var BABYLON;
  26231. (function (BABYLON) {
  26232. var BaseTexture = /** @class */ (function () {
  26233. function BaseTexture(scene) {
  26234. this._hasAlpha = false;
  26235. this.getAlphaFromRGB = false;
  26236. this.level = 1;
  26237. this.coordinatesIndex = 0;
  26238. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26239. /**
  26240. * | Value | Type | Description |
  26241. * | ----- | ------------------ | ----------- |
  26242. * | 0 | CLAMP_ADDRESSMODE | |
  26243. * | 1 | WRAP_ADDRESSMODE | |
  26244. * | 2 | MIRROR_ADDRESSMODE | |
  26245. */
  26246. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26247. /**
  26248. * | Value | Type | Description |
  26249. * | ----- | ------------------ | ----------- |
  26250. * | 0 | CLAMP_ADDRESSMODE | |
  26251. * | 1 | WRAP_ADDRESSMODE | |
  26252. * | 2 | MIRROR_ADDRESSMODE | |
  26253. */
  26254. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26255. /**
  26256. * | Value | Type | Description |
  26257. * | ----- | ------------------ | ----------- |
  26258. * | 0 | CLAMP_ADDRESSMODE | |
  26259. * | 1 | WRAP_ADDRESSMODE | |
  26260. * | 2 | MIRROR_ADDRESSMODE | |
  26261. */
  26262. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26263. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26264. this.isCube = false;
  26265. this.is3D = false;
  26266. this.gammaSpace = true;
  26267. this.invertZ = false;
  26268. this.lodLevelInAlpha = false;
  26269. this.lodGenerationOffset = 0.0;
  26270. this.lodGenerationScale = 0.8;
  26271. this.isRenderTarget = false;
  26272. this.animations = new Array();
  26273. /**
  26274. * An event triggered when the texture is disposed.
  26275. * @type {BABYLON.Observable}
  26276. */
  26277. this.onDisposeObservable = new BABYLON.Observable();
  26278. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26279. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26280. if (this._scene) {
  26281. this._scene.textures.push(this);
  26282. }
  26283. this._uid = null;
  26284. }
  26285. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26286. get: function () {
  26287. return this._hasAlpha;
  26288. },
  26289. set: function (value) {
  26290. if (this._hasAlpha === value) {
  26291. return;
  26292. }
  26293. this._hasAlpha = value;
  26294. if (this._scene) {
  26295. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26296. }
  26297. },
  26298. enumerable: true,
  26299. configurable: true
  26300. });
  26301. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26302. get: function () {
  26303. return this._coordinatesMode;
  26304. },
  26305. /**
  26306. * How a texture is mapped.
  26307. *
  26308. * | Value | Type | Description |
  26309. * | ----- | ----------------------------------- | ----------- |
  26310. * | 0 | EXPLICIT_MODE | |
  26311. * | 1 | SPHERICAL_MODE | |
  26312. * | 2 | PLANAR_MODE | |
  26313. * | 3 | CUBIC_MODE | |
  26314. * | 4 | PROJECTION_MODE | |
  26315. * | 5 | SKYBOX_MODE | |
  26316. * | 6 | INVCUBIC_MODE | |
  26317. * | 7 | EQUIRECTANGULAR_MODE | |
  26318. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26319. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26320. */
  26321. set: function (value) {
  26322. if (this._coordinatesMode === value) {
  26323. return;
  26324. }
  26325. this._coordinatesMode = value;
  26326. if (this._scene) {
  26327. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26328. }
  26329. },
  26330. enumerable: true,
  26331. configurable: true
  26332. });
  26333. Object.defineProperty(BaseTexture.prototype, "uid", {
  26334. get: function () {
  26335. if (!this._uid) {
  26336. this._uid = BABYLON.Tools.RandomId();
  26337. }
  26338. return this._uid;
  26339. },
  26340. enumerable: true,
  26341. configurable: true
  26342. });
  26343. BaseTexture.prototype.toString = function () {
  26344. return this.name;
  26345. };
  26346. BaseTexture.prototype.getClassName = function () {
  26347. return "BaseTexture";
  26348. };
  26349. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26350. set: function (callback) {
  26351. if (this._onDisposeObserver) {
  26352. this.onDisposeObservable.remove(this._onDisposeObserver);
  26353. }
  26354. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26355. },
  26356. enumerable: true,
  26357. configurable: true
  26358. });
  26359. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26360. get: function () {
  26361. return true;
  26362. },
  26363. enumerable: true,
  26364. configurable: true
  26365. });
  26366. BaseTexture.prototype.getScene = function () {
  26367. return this._scene;
  26368. };
  26369. BaseTexture.prototype.getTextureMatrix = function () {
  26370. return BABYLON.Matrix.IdentityReadOnly;
  26371. };
  26372. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26373. return BABYLON.Matrix.IdentityReadOnly;
  26374. };
  26375. BaseTexture.prototype.getInternalTexture = function () {
  26376. return this._texture;
  26377. };
  26378. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26379. return !this.isBlocking || this.isReady();
  26380. };
  26381. BaseTexture.prototype.isReady = function () {
  26382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26383. this.delayLoad();
  26384. return false;
  26385. }
  26386. if (this._texture) {
  26387. return this._texture.isReady;
  26388. }
  26389. return false;
  26390. };
  26391. BaseTexture.prototype.getSize = function () {
  26392. if (this._texture && this._texture.width) {
  26393. return new BABYLON.Size(this._texture.width, this._texture.height);
  26394. }
  26395. if (this._texture && this._texture._size) {
  26396. return new BABYLON.Size(this._texture._size, this._texture._size);
  26397. }
  26398. return BABYLON.Size.Zero();
  26399. };
  26400. BaseTexture.prototype.getBaseSize = function () {
  26401. if (!this.isReady() || !this._texture)
  26402. return BABYLON.Size.Zero();
  26403. if (this._texture._size) {
  26404. return new BABYLON.Size(this._texture._size, this._texture._size);
  26405. }
  26406. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26407. };
  26408. BaseTexture.prototype.scale = function (ratio) {
  26409. };
  26410. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26411. get: function () {
  26412. return false;
  26413. },
  26414. enumerable: true,
  26415. configurable: true
  26416. });
  26417. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26418. if (!this._scene) {
  26419. return null;
  26420. }
  26421. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26422. for (var index = 0; index < texturesCache.length; index++) {
  26423. var texturesCacheEntry = texturesCache[index];
  26424. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26425. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26426. texturesCacheEntry.incrementReferences();
  26427. return texturesCacheEntry;
  26428. }
  26429. }
  26430. }
  26431. return null;
  26432. };
  26433. BaseTexture.prototype._rebuild = function () {
  26434. };
  26435. BaseTexture.prototype.delayLoad = function () {
  26436. };
  26437. BaseTexture.prototype.clone = function () {
  26438. return null;
  26439. };
  26440. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26441. get: function () {
  26442. if (!this._texture) {
  26443. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26444. }
  26445. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26451. get: function () {
  26452. if (!this._texture) {
  26453. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26454. }
  26455. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. BaseTexture.prototype.readPixels = function (faceIndex) {
  26461. if (faceIndex === void 0) { faceIndex = 0; }
  26462. if (!this._texture) {
  26463. return null;
  26464. }
  26465. var size = this.getSize();
  26466. var scene = this.getScene();
  26467. if (!scene) {
  26468. return null;
  26469. }
  26470. var engine = scene.getEngine();
  26471. if (this._texture.isCube) {
  26472. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26473. }
  26474. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26475. };
  26476. BaseTexture.prototype.releaseInternalTexture = function () {
  26477. if (this._texture) {
  26478. this._texture.dispose();
  26479. this._texture = null;
  26480. }
  26481. };
  26482. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26483. get: function () {
  26484. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26485. return null;
  26486. }
  26487. if (!this._texture._sphericalPolynomial) {
  26488. this._texture._sphericalPolynomial =
  26489. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26490. }
  26491. return this._texture._sphericalPolynomial;
  26492. },
  26493. set: function (value) {
  26494. if (this._texture) {
  26495. this._texture._sphericalPolynomial = value;
  26496. }
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26502. get: function () {
  26503. if (this._texture) {
  26504. return this._texture._lodTextureHigh;
  26505. }
  26506. return null;
  26507. },
  26508. enumerable: true,
  26509. configurable: true
  26510. });
  26511. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26512. get: function () {
  26513. if (this._texture) {
  26514. return this._texture._lodTextureMid;
  26515. }
  26516. return null;
  26517. },
  26518. enumerable: true,
  26519. configurable: true
  26520. });
  26521. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26522. get: function () {
  26523. if (this._texture) {
  26524. return this._texture._lodTextureLow;
  26525. }
  26526. return null;
  26527. },
  26528. enumerable: true,
  26529. configurable: true
  26530. });
  26531. BaseTexture.prototype.dispose = function () {
  26532. if (!this._scene) {
  26533. return;
  26534. }
  26535. // Animations
  26536. this._scene.stopAnimation(this);
  26537. // Remove from scene
  26538. this._scene._removePendingData(this);
  26539. var index = this._scene.textures.indexOf(this);
  26540. if (index >= 0) {
  26541. this._scene.textures.splice(index, 1);
  26542. }
  26543. if (this._texture === undefined) {
  26544. return;
  26545. }
  26546. // Release
  26547. this.releaseInternalTexture();
  26548. // Callback
  26549. this.onDisposeObservable.notifyObservers(this);
  26550. this.onDisposeObservable.clear();
  26551. };
  26552. BaseTexture.prototype.serialize = function () {
  26553. if (!this.name) {
  26554. return null;
  26555. }
  26556. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26557. // Animations
  26558. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26559. return serializationObject;
  26560. };
  26561. BaseTexture.WhenAllReady = function (textures, callback) {
  26562. var numRemaining = textures.length;
  26563. if (numRemaining === 0) {
  26564. callback();
  26565. return;
  26566. }
  26567. var _loop_1 = function () {
  26568. texture = textures[i];
  26569. if (texture.isReady()) {
  26570. if (--numRemaining === 0) {
  26571. callback();
  26572. }
  26573. }
  26574. else {
  26575. onLoadObservable = texture.onLoadObservable;
  26576. var onLoadCallback_1 = function () {
  26577. onLoadObservable.removeCallback(onLoadCallback_1);
  26578. if (--numRemaining === 0) {
  26579. callback();
  26580. }
  26581. };
  26582. onLoadObservable.add(onLoadCallback_1);
  26583. }
  26584. };
  26585. var texture, onLoadObservable;
  26586. for (var i = 0; i < textures.length; i++) {
  26587. _loop_1();
  26588. }
  26589. };
  26590. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26591. __decorate([
  26592. BABYLON.serialize()
  26593. ], BaseTexture.prototype, "name", void 0);
  26594. __decorate([
  26595. BABYLON.serialize("hasAlpha")
  26596. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26597. __decorate([
  26598. BABYLON.serialize()
  26599. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26600. __decorate([
  26601. BABYLON.serialize()
  26602. ], BaseTexture.prototype, "level", void 0);
  26603. __decorate([
  26604. BABYLON.serialize()
  26605. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26606. __decorate([
  26607. BABYLON.serialize("coordinatesMode")
  26608. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26609. __decorate([
  26610. BABYLON.serialize()
  26611. ], BaseTexture.prototype, "wrapU", void 0);
  26612. __decorate([
  26613. BABYLON.serialize()
  26614. ], BaseTexture.prototype, "wrapV", void 0);
  26615. __decorate([
  26616. BABYLON.serialize()
  26617. ], BaseTexture.prototype, "wrapR", void 0);
  26618. __decorate([
  26619. BABYLON.serialize()
  26620. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26621. __decorate([
  26622. BABYLON.serialize()
  26623. ], BaseTexture.prototype, "isCube", void 0);
  26624. __decorate([
  26625. BABYLON.serialize()
  26626. ], BaseTexture.prototype, "is3D", void 0);
  26627. __decorate([
  26628. BABYLON.serialize()
  26629. ], BaseTexture.prototype, "gammaSpace", void 0);
  26630. __decorate([
  26631. BABYLON.serialize()
  26632. ], BaseTexture.prototype, "invertZ", void 0);
  26633. __decorate([
  26634. BABYLON.serialize()
  26635. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26636. __decorate([
  26637. BABYLON.serialize()
  26638. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26639. __decorate([
  26640. BABYLON.serialize()
  26641. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26642. __decorate([
  26643. BABYLON.serialize()
  26644. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26645. return BaseTexture;
  26646. }());
  26647. BABYLON.BaseTexture = BaseTexture;
  26648. })(BABYLON || (BABYLON = {}));
  26649. //# sourceMappingURL=babylon.baseTexture.js.map
  26650. var BABYLON;
  26651. (function (BABYLON) {
  26652. var Texture = /** @class */ (function (_super) {
  26653. __extends(Texture, _super);
  26654. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26655. if (noMipmap === void 0) { noMipmap = false; }
  26656. if (invertY === void 0) { invertY = true; }
  26657. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26658. if (onLoad === void 0) { onLoad = null; }
  26659. if (onError === void 0) { onError = null; }
  26660. if (buffer === void 0) { buffer = null; }
  26661. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26662. var _this = _super.call(this, scene) || this;
  26663. _this.uOffset = 0;
  26664. _this.vOffset = 0;
  26665. _this.uScale = 1.0;
  26666. _this.vScale = 1.0;
  26667. _this.uAng = 0;
  26668. _this.vAng = 0;
  26669. _this.wAng = 0;
  26670. _this._isBlocking = true;
  26671. _this.name = url || "";
  26672. _this.url = url;
  26673. _this._noMipmap = noMipmap;
  26674. _this._invertY = invertY;
  26675. _this._samplingMode = samplingMode;
  26676. _this._buffer = buffer;
  26677. _this._deleteBuffer = deleteBuffer;
  26678. if (format) {
  26679. _this._format = format;
  26680. }
  26681. scene = _this.getScene();
  26682. if (!scene) {
  26683. return _this;
  26684. }
  26685. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26686. var load = function () {
  26687. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26688. _this.onLoadObservable.notifyObservers(_this);
  26689. }
  26690. if (onLoad) {
  26691. onLoad();
  26692. }
  26693. if (!_this.isBlocking && scene) {
  26694. scene.resetCachedMaterial();
  26695. }
  26696. };
  26697. if (!_this.url) {
  26698. _this._delayedOnLoad = load;
  26699. _this._delayedOnError = onError;
  26700. return _this;
  26701. }
  26702. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26703. if (!_this._texture) {
  26704. if (!scene.useDelayedTextureLoading) {
  26705. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26706. if (deleteBuffer) {
  26707. delete _this._buffer;
  26708. }
  26709. }
  26710. else {
  26711. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26712. _this._delayedOnLoad = load;
  26713. _this._delayedOnError = onError;
  26714. }
  26715. }
  26716. else {
  26717. if (_this._texture.isReady) {
  26718. BABYLON.Tools.SetImmediate(function () { return load(); });
  26719. }
  26720. else {
  26721. _this._texture.onLoadedObservable.add(load);
  26722. }
  26723. }
  26724. return _this;
  26725. }
  26726. Object.defineProperty(Texture.prototype, "noMipmap", {
  26727. get: function () {
  26728. return this._noMipmap;
  26729. },
  26730. enumerable: true,
  26731. configurable: true
  26732. });
  26733. Object.defineProperty(Texture.prototype, "isBlocking", {
  26734. get: function () {
  26735. return this._isBlocking;
  26736. },
  26737. set: function (value) {
  26738. this._isBlocking = value;
  26739. },
  26740. enumerable: true,
  26741. configurable: true
  26742. });
  26743. Object.defineProperty(Texture.prototype, "samplingMode", {
  26744. get: function () {
  26745. return this._samplingMode;
  26746. },
  26747. enumerable: true,
  26748. configurable: true
  26749. });
  26750. Texture.prototype.updateURL = function (url) {
  26751. this.url = url;
  26752. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26753. this.delayLoad();
  26754. };
  26755. Texture.prototype.delayLoad = function () {
  26756. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26757. return;
  26758. }
  26759. var scene = this.getScene();
  26760. if (!scene) {
  26761. return;
  26762. }
  26763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26764. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26765. if (!this._texture) {
  26766. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26767. if (this._deleteBuffer) {
  26768. delete this._buffer;
  26769. }
  26770. }
  26771. else {
  26772. if (this._delayedOnLoad) {
  26773. if (this._texture.isReady) {
  26774. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26775. }
  26776. else {
  26777. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26778. }
  26779. }
  26780. }
  26781. this._delayedOnLoad = null;
  26782. this._delayedOnError = null;
  26783. };
  26784. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26785. if (!this._texture) {
  26786. return;
  26787. }
  26788. var scene = this.getScene();
  26789. if (!scene) {
  26790. return;
  26791. }
  26792. this._samplingMode = samplingMode;
  26793. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26794. };
  26795. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26796. x *= this.uScale;
  26797. y *= this.vScale;
  26798. x -= 0.5 * this.uScale;
  26799. y -= 0.5 * this.vScale;
  26800. z -= 0.5;
  26801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26802. t.x += 0.5 * this.uScale + this.uOffset;
  26803. t.y += 0.5 * this.vScale + this.vOffset;
  26804. t.z += 0.5;
  26805. };
  26806. Texture.prototype.getTextureMatrix = function () {
  26807. var _this = this;
  26808. if (this.uOffset === this._cachedUOffset &&
  26809. this.vOffset === this._cachedVOffset &&
  26810. this.uScale === this._cachedUScale &&
  26811. this.vScale === this._cachedVScale &&
  26812. this.uAng === this._cachedUAng &&
  26813. this.vAng === this._cachedVAng &&
  26814. this.wAng === this._cachedWAng) {
  26815. return this._cachedTextureMatrix;
  26816. }
  26817. this._cachedUOffset = this.uOffset;
  26818. this._cachedVOffset = this.vOffset;
  26819. this._cachedUScale = this.uScale;
  26820. this._cachedVScale = this.vScale;
  26821. this._cachedUAng = this.uAng;
  26822. this._cachedVAng = this.vAng;
  26823. this._cachedWAng = this.wAng;
  26824. if (!this._cachedTextureMatrix) {
  26825. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26826. this._rowGenerationMatrix = new BABYLON.Matrix();
  26827. this._t0 = BABYLON.Vector3.Zero();
  26828. this._t1 = BABYLON.Vector3.Zero();
  26829. this._t2 = BABYLON.Vector3.Zero();
  26830. }
  26831. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26832. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26833. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26834. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26835. this._t1.subtractInPlace(this._t0);
  26836. this._t2.subtractInPlace(this._t0);
  26837. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26838. this._cachedTextureMatrix.m[0] = this._t1.x;
  26839. this._cachedTextureMatrix.m[1] = this._t1.y;
  26840. this._cachedTextureMatrix.m[2] = this._t1.z;
  26841. this._cachedTextureMatrix.m[4] = this._t2.x;
  26842. this._cachedTextureMatrix.m[5] = this._t2.y;
  26843. this._cachedTextureMatrix.m[6] = this._t2.z;
  26844. this._cachedTextureMatrix.m[8] = this._t0.x;
  26845. this._cachedTextureMatrix.m[9] = this._t0.y;
  26846. this._cachedTextureMatrix.m[10] = this._t0.z;
  26847. var scene = this.getScene();
  26848. if (!scene) {
  26849. return this._cachedTextureMatrix;
  26850. }
  26851. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26852. return mat.hasTexture(_this);
  26853. });
  26854. return this._cachedTextureMatrix;
  26855. };
  26856. Texture.prototype.getReflectionTextureMatrix = function () {
  26857. var _this = this;
  26858. var scene = this.getScene();
  26859. if (!scene) {
  26860. return this._cachedTextureMatrix;
  26861. }
  26862. if (this.uOffset === this._cachedUOffset &&
  26863. this.vOffset === this._cachedVOffset &&
  26864. this.uScale === this._cachedUScale &&
  26865. this.vScale === this._cachedVScale &&
  26866. this.coordinatesMode === this._cachedCoordinatesMode) {
  26867. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26868. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26869. return this._cachedTextureMatrix;
  26870. }
  26871. }
  26872. else {
  26873. return this._cachedTextureMatrix;
  26874. }
  26875. }
  26876. if (!this._cachedTextureMatrix) {
  26877. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26878. }
  26879. if (!this._projectionModeMatrix) {
  26880. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26881. }
  26882. this._cachedUOffset = this.uOffset;
  26883. this._cachedVOffset = this.vOffset;
  26884. this._cachedUScale = this.uScale;
  26885. this._cachedVScale = this.vScale;
  26886. this._cachedCoordinatesMode = this.coordinatesMode;
  26887. switch (this.coordinatesMode) {
  26888. case Texture.PLANAR_MODE:
  26889. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26890. this._cachedTextureMatrix[0] = this.uScale;
  26891. this._cachedTextureMatrix[5] = this.vScale;
  26892. this._cachedTextureMatrix[12] = this.uOffset;
  26893. this._cachedTextureMatrix[13] = this.vOffset;
  26894. break;
  26895. case Texture.PROJECTION_MODE:
  26896. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26897. this._projectionModeMatrix.m[0] = 0.5;
  26898. this._projectionModeMatrix.m[5] = -0.5;
  26899. this._projectionModeMatrix.m[10] = 0.0;
  26900. this._projectionModeMatrix.m[12] = 0.5;
  26901. this._projectionModeMatrix.m[13] = 0.5;
  26902. this._projectionModeMatrix.m[14] = 1.0;
  26903. this._projectionModeMatrix.m[15] = 1.0;
  26904. var projectionMatrix = scene.getProjectionMatrix();
  26905. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26906. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26907. break;
  26908. default:
  26909. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26910. break;
  26911. }
  26912. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26913. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26914. });
  26915. return this._cachedTextureMatrix;
  26916. };
  26917. Texture.prototype.clone = function () {
  26918. var _this = this;
  26919. return BABYLON.SerializationHelper.Clone(function () {
  26920. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26921. }, this);
  26922. };
  26923. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26924. get: function () {
  26925. if (!this._onLoadObservable) {
  26926. this._onLoadObservable = new BABYLON.Observable();
  26927. }
  26928. return this._onLoadObservable;
  26929. },
  26930. enumerable: true,
  26931. configurable: true
  26932. });
  26933. Texture.prototype.serialize = function () {
  26934. var serializationObject = _super.prototype.serialize.call(this);
  26935. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26936. serializationObject.base64String = this._buffer;
  26937. serializationObject.name = serializationObject.name.replace("data:", "");
  26938. }
  26939. return serializationObject;
  26940. };
  26941. Texture.prototype.getClassName = function () {
  26942. return "Texture";
  26943. };
  26944. Texture.prototype.dispose = function () {
  26945. _super.prototype.dispose.call(this);
  26946. if (this.onLoadObservable) {
  26947. this.onLoadObservable.clear();
  26948. this._onLoadObservable = null;
  26949. }
  26950. this._delayedOnLoad = null;
  26951. this._delayedOnError = null;
  26952. };
  26953. // Statics
  26954. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26955. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26956. if (onLoad === void 0) { onLoad = null; }
  26957. if (onError === void 0) { onError = null; }
  26958. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26959. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26960. };
  26961. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26962. if (parsedTexture.customType) {
  26963. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26964. // Update Sampling Mode
  26965. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26966. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26967. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26968. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26969. }
  26970. }
  26971. return parsedCustomTexture;
  26972. }
  26973. if (parsedTexture.isCube) {
  26974. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26975. }
  26976. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26977. return null;
  26978. }
  26979. var texture = BABYLON.SerializationHelper.Parse(function () {
  26980. var generateMipMaps = true;
  26981. if (parsedTexture.noMipmap) {
  26982. generateMipMaps = false;
  26983. }
  26984. if (parsedTexture.mirrorPlane) {
  26985. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26986. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26987. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26988. return mirrorTexture;
  26989. }
  26990. else if (parsedTexture.isRenderTarget) {
  26991. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26992. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26993. return renderTargetTexture;
  26994. }
  26995. else {
  26996. var texture;
  26997. if (parsedTexture.base64String) {
  26998. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26999. }
  27000. else {
  27001. var url = rootUrl + parsedTexture.name;
  27002. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27003. url = parsedTexture.url;
  27004. }
  27005. texture = new Texture(url, scene, !generateMipMaps);
  27006. }
  27007. return texture;
  27008. }
  27009. }, parsedTexture, scene);
  27010. // Update Sampling Mode
  27011. if (parsedTexture.samplingMode) {
  27012. var sampling = parsedTexture.samplingMode;
  27013. if (texture._samplingMode !== sampling) {
  27014. texture.updateSamplingMode(sampling);
  27015. }
  27016. }
  27017. // Animations
  27018. if (parsedTexture.animations) {
  27019. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27020. var parsedAnimation = parsedTexture.animations[animationIndex];
  27021. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27022. }
  27023. }
  27024. return texture;
  27025. };
  27026. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27027. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27028. if (noMipmap === void 0) { noMipmap = false; }
  27029. if (invertY === void 0) { invertY = true; }
  27030. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27031. if (onLoad === void 0) { onLoad = null; }
  27032. if (onError === void 0) { onError = null; }
  27033. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27034. if (name.substr(0, 5) !== "data:") {
  27035. name = "data:" + name;
  27036. }
  27037. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27038. };
  27039. // Constants
  27040. Texture.NEAREST_SAMPLINGMODE = 1;
  27041. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27042. Texture.BILINEAR_SAMPLINGMODE = 2;
  27043. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27044. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27045. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27046. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27047. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27048. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27049. Texture.NEAREST_LINEAR = 7;
  27050. Texture.NEAREST_NEAREST = 8;
  27051. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27052. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27053. Texture.LINEAR_LINEAR = 11;
  27054. Texture.LINEAR_NEAREST = 12;
  27055. Texture.EXPLICIT_MODE = 0;
  27056. Texture.SPHERICAL_MODE = 1;
  27057. Texture.PLANAR_MODE = 2;
  27058. Texture.CUBIC_MODE = 3;
  27059. Texture.PROJECTION_MODE = 4;
  27060. Texture.SKYBOX_MODE = 5;
  27061. Texture.INVCUBIC_MODE = 6;
  27062. Texture.EQUIRECTANGULAR_MODE = 7;
  27063. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27064. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27065. Texture.CLAMP_ADDRESSMODE = 0;
  27066. Texture.WRAP_ADDRESSMODE = 1;
  27067. Texture.MIRROR_ADDRESSMODE = 2;
  27068. /**
  27069. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27070. */
  27071. Texture.UseSerializedUrlIfAny = false;
  27072. __decorate([
  27073. BABYLON.serialize()
  27074. ], Texture.prototype, "url", void 0);
  27075. __decorate([
  27076. BABYLON.serialize()
  27077. ], Texture.prototype, "uOffset", void 0);
  27078. __decorate([
  27079. BABYLON.serialize()
  27080. ], Texture.prototype, "vOffset", void 0);
  27081. __decorate([
  27082. BABYLON.serialize()
  27083. ], Texture.prototype, "uScale", void 0);
  27084. __decorate([
  27085. BABYLON.serialize()
  27086. ], Texture.prototype, "vScale", void 0);
  27087. __decorate([
  27088. BABYLON.serialize()
  27089. ], Texture.prototype, "uAng", void 0);
  27090. __decorate([
  27091. BABYLON.serialize()
  27092. ], Texture.prototype, "vAng", void 0);
  27093. __decorate([
  27094. BABYLON.serialize()
  27095. ], Texture.prototype, "wAng", void 0);
  27096. __decorate([
  27097. BABYLON.serialize()
  27098. ], Texture.prototype, "isBlocking", null);
  27099. return Texture;
  27100. }(BABYLON.BaseTexture));
  27101. BABYLON.Texture = Texture;
  27102. })(BABYLON || (BABYLON = {}));
  27103. //# sourceMappingURL=babylon.texture.js.map
  27104. var BABYLON;
  27105. (function (BABYLON) {
  27106. var _InstancesBatch = /** @class */ (function () {
  27107. function _InstancesBatch() {
  27108. this.mustReturn = false;
  27109. this.visibleInstances = new Array();
  27110. this.renderSelf = new Array();
  27111. }
  27112. return _InstancesBatch;
  27113. }());
  27114. BABYLON._InstancesBatch = _InstancesBatch;
  27115. var Mesh = /** @class */ (function (_super) {
  27116. __extends(Mesh, _super);
  27117. /**
  27118. * @constructor
  27119. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27120. * @param {Scene} scene The scene to add this mesh to.
  27121. * @param {Node} parent The parent of this mesh, if it has one
  27122. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27123. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27124. * When false, achieved by calling a clone(), also passing False.
  27125. * This will make creation of children, recursive.
  27126. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27127. */
  27128. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27129. if (scene === void 0) { scene = null; }
  27130. if (parent === void 0) { parent = null; }
  27131. if (source === void 0) { source = null; }
  27132. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27133. var _this = _super.call(this, name, scene) || this;
  27134. // Events
  27135. /**
  27136. * An event triggered before rendering the mesh
  27137. * @type {BABYLON.Observable}
  27138. */
  27139. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27140. /**
  27141. * An event triggered after rendering the mesh
  27142. * @type {BABYLON.Observable}
  27143. */
  27144. _this.onAfterRenderObservable = new BABYLON.Observable();
  27145. /**
  27146. * An event triggered before drawing the mesh
  27147. * @type {BABYLON.Observable}
  27148. */
  27149. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27150. // Members
  27151. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27152. _this.instances = new Array();
  27153. _this._LODLevels = new Array();
  27154. _this._visibleInstances = {};
  27155. _this._renderIdForInstances = new Array();
  27156. _this._batchCache = new _InstancesBatch();
  27157. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27158. // Use by builder only to know what orientation were the mesh build in.
  27159. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27160. _this.overrideMaterialSideOrientation = null;
  27161. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27162. // Will be used to save a source mesh reference, If any
  27163. _this._source = null;
  27164. scene = _this.getScene();
  27165. if (source) {
  27166. // Source mesh
  27167. _this._source = source;
  27168. // Geometry
  27169. if (source._geometry) {
  27170. source._geometry.applyToMesh(_this);
  27171. }
  27172. // Deep copy
  27173. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27174. // Metadata
  27175. if (source.metadata && source.metadata.clone) {
  27176. _this.metadata = source.metadata.clone();
  27177. }
  27178. else {
  27179. _this.metadata = source.metadata;
  27180. }
  27181. // Tags
  27182. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27183. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27184. }
  27185. // Parent
  27186. _this.parent = source.parent;
  27187. // Pivot
  27188. _this.setPivotMatrix(source.getPivotMatrix());
  27189. _this.id = name + "." + source.id;
  27190. // Material
  27191. _this.material = source.material;
  27192. var index;
  27193. if (!doNotCloneChildren) {
  27194. // Children
  27195. var directDescendants = source.getDescendants(true);
  27196. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27197. var child = directDescendants[index_1];
  27198. if (child.clone) {
  27199. child.clone(name + "." + child.name, _this);
  27200. }
  27201. }
  27202. }
  27203. // Physics clone
  27204. var physicsEngine = _this.getScene().getPhysicsEngine();
  27205. if (clonePhysicsImpostor && physicsEngine) {
  27206. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27207. if (impostor) {
  27208. _this.physicsImpostor = impostor.clone(_this);
  27209. }
  27210. }
  27211. // Particles
  27212. for (index = 0; index < scene.particleSystems.length; index++) {
  27213. var system = scene.particleSystems[index];
  27214. if (system.emitter === source) {
  27215. system.clone(system.name, _this);
  27216. }
  27217. }
  27218. _this.computeWorldMatrix(true);
  27219. }
  27220. // Parent
  27221. if (parent !== null) {
  27222. _this.parent = parent;
  27223. }
  27224. return _this;
  27225. }
  27226. Object.defineProperty(Mesh, "FRONTSIDE", {
  27227. /**
  27228. * Mesh side orientation : usually the external or front surface
  27229. */
  27230. get: function () {
  27231. return Mesh._FRONTSIDE;
  27232. },
  27233. enumerable: true,
  27234. configurable: true
  27235. });
  27236. Object.defineProperty(Mesh, "BACKSIDE", {
  27237. /**
  27238. * Mesh side orientation : usually the internal or back surface
  27239. */
  27240. get: function () {
  27241. return Mesh._BACKSIDE;
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27247. /**
  27248. * Mesh side orientation : both internal and external or front and back surfaces
  27249. */
  27250. get: function () {
  27251. return Mesh._DOUBLESIDE;
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27257. /**
  27258. * Mesh side orientation : by default, `FRONTSIDE`
  27259. */
  27260. get: function () {
  27261. return Mesh._DEFAULTSIDE;
  27262. },
  27263. enumerable: true,
  27264. configurable: true
  27265. });
  27266. Object.defineProperty(Mesh, "NO_CAP", {
  27267. /**
  27268. * Mesh cap setting : no cap
  27269. */
  27270. get: function () {
  27271. return Mesh._NO_CAP;
  27272. },
  27273. enumerable: true,
  27274. configurable: true
  27275. });
  27276. Object.defineProperty(Mesh, "CAP_START", {
  27277. /**
  27278. * Mesh cap setting : one cap at the beginning of the mesh
  27279. */
  27280. get: function () {
  27281. return Mesh._CAP_START;
  27282. },
  27283. enumerable: true,
  27284. configurable: true
  27285. });
  27286. Object.defineProperty(Mesh, "CAP_END", {
  27287. /**
  27288. * Mesh cap setting : one cap at the end of the mesh
  27289. */
  27290. get: function () {
  27291. return Mesh._CAP_END;
  27292. },
  27293. enumerable: true,
  27294. configurable: true
  27295. });
  27296. Object.defineProperty(Mesh, "CAP_ALL", {
  27297. /**
  27298. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27299. */
  27300. get: function () {
  27301. return Mesh._CAP_ALL;
  27302. },
  27303. enumerable: true,
  27304. configurable: true
  27305. });
  27306. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27307. set: function (callback) {
  27308. if (this._onBeforeDrawObserver) {
  27309. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27310. }
  27311. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27312. },
  27313. enumerable: true,
  27314. configurable: true
  27315. });
  27316. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27317. get: function () {
  27318. return this._morphTargetManager;
  27319. },
  27320. set: function (value) {
  27321. if (this._morphTargetManager === value) {
  27322. return;
  27323. }
  27324. this._morphTargetManager = value;
  27325. this._syncGeometryWithMorphTargetManager();
  27326. },
  27327. enumerable: true,
  27328. configurable: true
  27329. });
  27330. Object.defineProperty(Mesh.prototype, "source", {
  27331. get: function () {
  27332. return this._source;
  27333. },
  27334. enumerable: true,
  27335. configurable: true
  27336. });
  27337. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27338. get: function () {
  27339. return this._unIndexed;
  27340. },
  27341. set: function (value) {
  27342. if (this._unIndexed !== value) {
  27343. this._unIndexed = value;
  27344. this._markSubMeshesAsAttributesDirty();
  27345. }
  27346. },
  27347. enumerable: true,
  27348. configurable: true
  27349. });
  27350. // Methods
  27351. /**
  27352. * Returns the string "Mesh".
  27353. */
  27354. Mesh.prototype.getClassName = function () {
  27355. return "Mesh";
  27356. };
  27357. /**
  27358. * Returns a string.
  27359. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27360. */
  27361. Mesh.prototype.toString = function (fullDetails) {
  27362. var ret = _super.prototype.toString.call(this, fullDetails);
  27363. ret += ", n vertices: " + this.getTotalVertices();
  27364. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27365. if (this.animations) {
  27366. for (var i = 0; i < this.animations.length; i++) {
  27367. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27368. }
  27369. }
  27370. if (fullDetails) {
  27371. if (this._geometry) {
  27372. var ib = this.getIndices();
  27373. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27374. if (vb && ib) {
  27375. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27376. }
  27377. }
  27378. else {
  27379. ret += ", flat shading: UNKNOWN";
  27380. }
  27381. }
  27382. return ret;
  27383. };
  27384. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27385. /**
  27386. * True if the mesh has some Levels Of Details (LOD).
  27387. * Returns a boolean.
  27388. */
  27389. get: function () {
  27390. return this._LODLevels.length > 0;
  27391. },
  27392. enumerable: true,
  27393. configurable: true
  27394. });
  27395. /**
  27396. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27397. * @returns an array of {BABYLON.MeshLODLevel}
  27398. */
  27399. Mesh.prototype.getLODLevels = function () {
  27400. return this._LODLevels;
  27401. };
  27402. Mesh.prototype._sortLODLevels = function () {
  27403. this._LODLevels.sort(function (a, b) {
  27404. if (a.distance < b.distance) {
  27405. return 1;
  27406. }
  27407. if (a.distance > b.distance) {
  27408. return -1;
  27409. }
  27410. return 0;
  27411. });
  27412. };
  27413. /**
  27414. * Add a mesh as LOD level triggered at the given distance.
  27415. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27416. * @param {number} distance The distance from the center of the object to show this level
  27417. * @param {Mesh} mesh The mesh to be added as LOD level
  27418. * @return {Mesh} This mesh (for chaining)
  27419. */
  27420. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27421. if (mesh && mesh._masterMesh) {
  27422. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27423. return this;
  27424. }
  27425. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27426. this._LODLevels.push(level);
  27427. if (mesh) {
  27428. mesh._masterMesh = this;
  27429. }
  27430. this._sortLODLevels();
  27431. return this;
  27432. };
  27433. /**
  27434. * Returns the LOD level mesh at the passed distance or null if not found.
  27435. * It is related to the method `addLODLevel(distance, mesh)`.
  27436. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27437. * Returns an object Mesh or `null`.
  27438. */
  27439. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27440. for (var index = 0; index < this._LODLevels.length; index++) {
  27441. var level = this._LODLevels[index];
  27442. if (level.distance === distance) {
  27443. return level.mesh;
  27444. }
  27445. }
  27446. return null;
  27447. };
  27448. /**
  27449. * Remove a mesh from the LOD array
  27450. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27451. * @param {Mesh} mesh The mesh to be removed.
  27452. * @return {Mesh} This mesh (for chaining)
  27453. */
  27454. Mesh.prototype.removeLODLevel = function (mesh) {
  27455. for (var index = 0; index < this._LODLevels.length; index++) {
  27456. if (this._LODLevels[index].mesh === mesh) {
  27457. this._LODLevels.splice(index, 1);
  27458. if (mesh) {
  27459. mesh._masterMesh = null;
  27460. }
  27461. }
  27462. }
  27463. this._sortLODLevels();
  27464. return this;
  27465. };
  27466. /**
  27467. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27468. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27469. */
  27470. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27471. if (!this._LODLevels || this._LODLevels.length === 0) {
  27472. return this;
  27473. }
  27474. var bSphere;
  27475. if (boundingSphere) {
  27476. bSphere = boundingSphere;
  27477. }
  27478. else {
  27479. var boundingInfo = this.getBoundingInfo();
  27480. bSphere = boundingInfo.boundingSphere;
  27481. }
  27482. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27483. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27484. if (this.onLODLevelSelection) {
  27485. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27486. }
  27487. return this;
  27488. }
  27489. for (var index = 0; index < this._LODLevels.length; index++) {
  27490. var level = this._LODLevels[index];
  27491. if (level.distance < distanceToCamera) {
  27492. if (level.mesh) {
  27493. level.mesh._preActivate();
  27494. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27495. }
  27496. if (this.onLODLevelSelection) {
  27497. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27498. }
  27499. return level.mesh;
  27500. }
  27501. }
  27502. if (this.onLODLevelSelection) {
  27503. this.onLODLevelSelection(distanceToCamera, this, this);
  27504. }
  27505. return this;
  27506. };
  27507. Object.defineProperty(Mesh.prototype, "geometry", {
  27508. /**
  27509. * Returns the mesh internal Geometry object.
  27510. */
  27511. get: function () {
  27512. return this._geometry;
  27513. },
  27514. enumerable: true,
  27515. configurable: true
  27516. });
  27517. /**
  27518. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27519. */
  27520. Mesh.prototype.getTotalVertices = function () {
  27521. if (this._geometry === null || this._geometry === undefined) {
  27522. return 0;
  27523. }
  27524. return this._geometry.getTotalVertices();
  27525. };
  27526. /**
  27527. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27528. * 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.
  27529. * You can force the copy with forceCopy === true
  27530. * Returns null if the mesh has no geometry or no vertex buffer.
  27531. * Possible `kind` values :
  27532. * - BABYLON.VertexBuffer.PositionKind
  27533. * - BABYLON.VertexBuffer.UVKind
  27534. * - BABYLON.VertexBuffer.UV2Kind
  27535. * - BABYLON.VertexBuffer.UV3Kind
  27536. * - BABYLON.VertexBuffer.UV4Kind
  27537. * - BABYLON.VertexBuffer.UV5Kind
  27538. * - BABYLON.VertexBuffer.UV6Kind
  27539. * - BABYLON.VertexBuffer.ColorKind
  27540. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27541. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27542. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27543. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27544. */
  27545. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27546. if (!this._geometry) {
  27547. return null;
  27548. }
  27549. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27550. };
  27551. /**
  27552. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27553. * Returns `null` if the mesh has no geometry.
  27554. * Possible `kind` values :
  27555. * - BABYLON.VertexBuffer.PositionKind
  27556. * - BABYLON.VertexBuffer.UVKind
  27557. * - BABYLON.VertexBuffer.UV2Kind
  27558. * - BABYLON.VertexBuffer.UV3Kind
  27559. * - BABYLON.VertexBuffer.UV4Kind
  27560. * - BABYLON.VertexBuffer.UV5Kind
  27561. * - BABYLON.VertexBuffer.UV6Kind
  27562. * - BABYLON.VertexBuffer.ColorKind
  27563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27567. */
  27568. Mesh.prototype.getVertexBuffer = function (kind) {
  27569. if (!this._geometry) {
  27570. return null;
  27571. }
  27572. return this._geometry.getVertexBuffer(kind);
  27573. };
  27574. /**
  27575. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27576. * Possible `kind` values :
  27577. * - BABYLON.VertexBuffer.PositionKind
  27578. * - BABYLON.VertexBuffer.UVKind
  27579. * - BABYLON.VertexBuffer.UV2Kind
  27580. * - BABYLON.VertexBuffer.UV3Kind
  27581. * - BABYLON.VertexBuffer.UV4Kind
  27582. * - BABYLON.VertexBuffer.UV5Kind
  27583. * - BABYLON.VertexBuffer.UV6Kind
  27584. * - BABYLON.VertexBuffer.ColorKind
  27585. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27586. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27587. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27588. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27589. */
  27590. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27591. if (!this._geometry) {
  27592. if (this._delayInfo) {
  27593. return this._delayInfo.indexOf(kind) !== -1;
  27594. }
  27595. return false;
  27596. }
  27597. return this._geometry.isVerticesDataPresent(kind);
  27598. };
  27599. /**
  27600. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27601. * Possible `kind` values :
  27602. * - BABYLON.VertexBuffer.PositionKind
  27603. * - BABYLON.VertexBuffer.UVKind
  27604. * - BABYLON.VertexBuffer.UV2Kind
  27605. * - BABYLON.VertexBuffer.UV3Kind
  27606. * - BABYLON.VertexBuffer.UV4Kind
  27607. * - BABYLON.VertexBuffer.UV5Kind
  27608. * - BABYLON.VertexBuffer.UV6Kind
  27609. * - BABYLON.VertexBuffer.ColorKind
  27610. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27611. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27612. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27613. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27614. */
  27615. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27616. if (!this._geometry) {
  27617. if (this._delayInfo) {
  27618. return this._delayInfo.indexOf(kind) !== -1;
  27619. }
  27620. return false;
  27621. }
  27622. return this._geometry.isVertexBufferUpdatable(kind);
  27623. };
  27624. /**
  27625. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27626. * Possible `kind` values :
  27627. * - BABYLON.VertexBuffer.PositionKind
  27628. * - BABYLON.VertexBuffer.UVKind
  27629. * - BABYLON.VertexBuffer.UV2Kind
  27630. * - BABYLON.VertexBuffer.UV3Kind
  27631. * - BABYLON.VertexBuffer.UV4Kind
  27632. * - BABYLON.VertexBuffer.UV5Kind
  27633. * - BABYLON.VertexBuffer.UV6Kind
  27634. * - BABYLON.VertexBuffer.ColorKind
  27635. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27636. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27637. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27638. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27639. */
  27640. Mesh.prototype.getVerticesDataKinds = function () {
  27641. if (!this._geometry) {
  27642. var result = new Array();
  27643. if (this._delayInfo) {
  27644. this._delayInfo.forEach(function (kind, index, array) {
  27645. result.push(kind);
  27646. });
  27647. }
  27648. return result;
  27649. }
  27650. return this._geometry.getVerticesDataKinds();
  27651. };
  27652. /**
  27653. * Returns a positive integer : the total number of indices in this mesh geometry.
  27654. * Returns zero if the mesh has no geometry.
  27655. */
  27656. Mesh.prototype.getTotalIndices = function () {
  27657. if (!this._geometry) {
  27658. return 0;
  27659. }
  27660. return this._geometry.getTotalIndices();
  27661. };
  27662. /**
  27663. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27664. * 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.
  27665. * Returns an empty array if the mesh has no geometry.
  27666. */
  27667. Mesh.prototype.getIndices = function (copyWhenShared) {
  27668. if (!this._geometry) {
  27669. return [];
  27670. }
  27671. return this._geometry.getIndices(copyWhenShared);
  27672. };
  27673. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27674. get: function () {
  27675. return this._masterMesh !== null && this._masterMesh !== undefined;
  27676. },
  27677. enumerable: true,
  27678. configurable: true
  27679. });
  27680. /**
  27681. * Determine if the current mesh is ready to be rendered
  27682. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27683. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27684. * @returns true if all associated assets are ready (material, textures, shaders)
  27685. */
  27686. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27687. if (completeCheck === void 0) { completeCheck = false; }
  27688. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27689. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27690. return false;
  27691. }
  27692. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27693. return false;
  27694. }
  27695. if (!this.subMeshes || this.subMeshes.length === 0) {
  27696. return true;
  27697. }
  27698. if (!completeCheck) {
  27699. return true;
  27700. }
  27701. var engine = this.getEngine();
  27702. var scene = this.getScene();
  27703. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27704. this.computeWorldMatrix();
  27705. var mat = this.material || scene.defaultMaterial;
  27706. if (mat) {
  27707. if (mat.storeEffectOnSubMeshes) {
  27708. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27709. var subMesh = _a[_i];
  27710. var effectiveMaterial = subMesh.getMaterial();
  27711. if (effectiveMaterial) {
  27712. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27713. return false;
  27714. }
  27715. }
  27716. }
  27717. }
  27718. else {
  27719. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27720. return false;
  27721. }
  27722. }
  27723. }
  27724. // Shadows
  27725. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27726. var light = _c[_b];
  27727. var generator = light.getShadowGenerator();
  27728. if (generator) {
  27729. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27730. var subMesh = _e[_d];
  27731. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27732. return false;
  27733. }
  27734. }
  27735. }
  27736. }
  27737. // LOD
  27738. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27739. var lod = _g[_f];
  27740. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27741. return false;
  27742. }
  27743. }
  27744. return true;
  27745. };
  27746. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27747. /**
  27748. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27749. * This property is pertinent only for updatable parametric shapes.
  27750. */
  27751. get: function () {
  27752. return this._areNormalsFrozen;
  27753. },
  27754. enumerable: true,
  27755. configurable: true
  27756. });
  27757. /**
  27758. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27759. * It has no effect at all on other shapes.
  27760. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27761. * Returns the Mesh.
  27762. */
  27763. Mesh.prototype.freezeNormals = function () {
  27764. this._areNormalsFrozen = true;
  27765. return this;
  27766. };
  27767. /**
  27768. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27769. * It has no effect at all on other shapes.
  27770. * It reactivates the mesh normals computation if it was previously frozen.
  27771. * Returns the Mesh.
  27772. */
  27773. Mesh.prototype.unfreezeNormals = function () {
  27774. this._areNormalsFrozen = false;
  27775. return this;
  27776. };
  27777. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27778. /**
  27779. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27780. */
  27781. set: function (count) {
  27782. this._overridenInstanceCount = count;
  27783. },
  27784. enumerable: true,
  27785. configurable: true
  27786. });
  27787. // Methods
  27788. Mesh.prototype._preActivate = function () {
  27789. var sceneRenderId = this.getScene().getRenderId();
  27790. if (this._preActivateId === sceneRenderId) {
  27791. return this;
  27792. }
  27793. this._preActivateId = sceneRenderId;
  27794. this._visibleInstances = null;
  27795. return this;
  27796. };
  27797. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27798. if (this._visibleInstances) {
  27799. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27800. }
  27801. return this;
  27802. };
  27803. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27804. if (!this._visibleInstances) {
  27805. this._visibleInstances = {};
  27806. this._visibleInstances.defaultRenderId = renderId;
  27807. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27808. }
  27809. if (!this._visibleInstances[renderId]) {
  27810. this._visibleInstances[renderId] = new Array();
  27811. }
  27812. this._visibleInstances[renderId].push(instance);
  27813. return this;
  27814. };
  27815. /**
  27816. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27817. * This means the mesh underlying bounding box and sphere are recomputed.
  27818. * Returns the Mesh.
  27819. */
  27820. Mesh.prototype.refreshBoundingInfo = function () {
  27821. return this._refreshBoundingInfo(false);
  27822. };
  27823. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27824. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27825. return this;
  27826. }
  27827. var data = this._getPositionData(applySkeleton);
  27828. if (data) {
  27829. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27830. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27831. }
  27832. if (this.subMeshes) {
  27833. for (var index = 0; index < this.subMeshes.length; index++) {
  27834. this.subMeshes[index].refreshBoundingInfo();
  27835. }
  27836. }
  27837. this._updateBoundingInfo();
  27838. return this;
  27839. };
  27840. Mesh.prototype._getPositionData = function (applySkeleton) {
  27841. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27842. if (data && applySkeleton && this.skeleton) {
  27843. data = BABYLON.Tools.Slice(data);
  27844. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27845. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27846. if (matricesWeightsData && matricesIndicesData) {
  27847. var needExtras = this.numBoneInfluencers > 4;
  27848. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27849. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27850. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27851. var tempVector = BABYLON.Tmp.Vector3[0];
  27852. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27853. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27854. var matWeightIdx = 0;
  27855. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27856. finalMatrix.reset();
  27857. var inf;
  27858. var weight;
  27859. for (inf = 0; inf < 4; inf++) {
  27860. weight = matricesWeightsData[matWeightIdx + inf];
  27861. if (weight <= 0)
  27862. break;
  27863. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27864. finalMatrix.addToSelf(tempMatrix);
  27865. }
  27866. if (needExtras) {
  27867. for (inf = 0; inf < 4; inf++) {
  27868. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27869. if (weight <= 0)
  27870. break;
  27871. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27872. finalMatrix.addToSelf(tempMatrix);
  27873. }
  27874. }
  27875. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27876. tempVector.toArray(data, index);
  27877. }
  27878. }
  27879. }
  27880. return data;
  27881. };
  27882. Mesh.prototype._createGlobalSubMesh = function (force) {
  27883. var totalVertices = this.getTotalVertices();
  27884. if (!totalVertices || !this.getIndices()) {
  27885. return null;
  27886. }
  27887. // Check if we need to recreate the submeshes
  27888. if (this.subMeshes && this.subMeshes.length > 0) {
  27889. var ib = this.getIndices();
  27890. if (!ib) {
  27891. return null;
  27892. }
  27893. var totalIndices = ib.length;
  27894. var needToRecreate = false;
  27895. if (force) {
  27896. needToRecreate = true;
  27897. }
  27898. else {
  27899. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27900. var submesh = _a[_i];
  27901. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27902. needToRecreate = true;
  27903. break;
  27904. }
  27905. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27906. needToRecreate = true;
  27907. break;
  27908. }
  27909. }
  27910. }
  27911. if (!needToRecreate) {
  27912. return this.subMeshes[0];
  27913. }
  27914. }
  27915. this.releaseSubMeshes();
  27916. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27917. };
  27918. Mesh.prototype.subdivide = function (count) {
  27919. if (count < 1) {
  27920. return;
  27921. }
  27922. var totalIndices = this.getTotalIndices();
  27923. var subdivisionSize = (totalIndices / count) | 0;
  27924. var offset = 0;
  27925. // Ensure that subdivisionSize is a multiple of 3
  27926. while (subdivisionSize % 3 !== 0) {
  27927. subdivisionSize++;
  27928. }
  27929. this.releaseSubMeshes();
  27930. for (var index = 0; index < count; index++) {
  27931. if (offset >= totalIndices) {
  27932. break;
  27933. }
  27934. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27935. offset += subdivisionSize;
  27936. }
  27937. this.synchronizeInstances();
  27938. };
  27939. /**
  27940. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27941. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27942. * The `data` are either a numeric array either a Float32Array.
  27943. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27944. * 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).
  27945. * Note that a new underlying VertexBuffer object is created each call.
  27946. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27947. *
  27948. * Possible `kind` values :
  27949. * - BABYLON.VertexBuffer.PositionKind
  27950. * - BABYLON.VertexBuffer.UVKind
  27951. * - BABYLON.VertexBuffer.UV2Kind
  27952. * - BABYLON.VertexBuffer.UV3Kind
  27953. * - BABYLON.VertexBuffer.UV4Kind
  27954. * - BABYLON.VertexBuffer.UV5Kind
  27955. * - BABYLON.VertexBuffer.UV6Kind
  27956. * - BABYLON.VertexBuffer.ColorKind
  27957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27961. *
  27962. * Returns the Mesh.
  27963. */
  27964. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27965. if (updatable === void 0) { updatable = false; }
  27966. if (!this._geometry) {
  27967. var vertexData = new BABYLON.VertexData();
  27968. vertexData.set(data, kind);
  27969. var scene = this.getScene();
  27970. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27971. }
  27972. else {
  27973. this._geometry.setVerticesData(kind, data, updatable, stride);
  27974. }
  27975. return this;
  27976. };
  27977. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27978. if (updatable === void 0) { updatable = true; }
  27979. var vb = this.getVertexBuffer(kind);
  27980. if (!vb || vb.isUpdatable() === updatable) {
  27981. return;
  27982. }
  27983. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27984. };
  27985. /**
  27986. * Sets the mesh VertexBuffer.
  27987. * Returns the Mesh.
  27988. */
  27989. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27990. if (!this._geometry) {
  27991. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27992. }
  27993. this._geometry.setVerticesBuffer(buffer);
  27994. return this;
  27995. };
  27996. /**
  27997. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27998. * If the mesh has no geometry, it is simply returned as it is.
  27999. * The `data` are either a numeric array either a Float32Array.
  28000. * No new underlying VertexBuffer object is created.
  28001. * 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.
  28002. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28003. *
  28004. * Possible `kind` values :
  28005. * - BABYLON.VertexBuffer.PositionKind
  28006. * - BABYLON.VertexBuffer.UVKind
  28007. * - BABYLON.VertexBuffer.UV2Kind
  28008. * - BABYLON.VertexBuffer.UV3Kind
  28009. * - BABYLON.VertexBuffer.UV4Kind
  28010. * - BABYLON.VertexBuffer.UV5Kind
  28011. * - BABYLON.VertexBuffer.UV6Kind
  28012. * - BABYLON.VertexBuffer.ColorKind
  28013. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28014. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28015. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28016. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28017. *
  28018. * Returns the Mesh.
  28019. */
  28020. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28021. if (!this._geometry) {
  28022. return this;
  28023. }
  28024. if (!makeItUnique) {
  28025. this._geometry.updateVerticesData(kind, data, updateExtends);
  28026. }
  28027. else {
  28028. this.makeGeometryUnique();
  28029. this.updateVerticesData(kind, data, updateExtends, false);
  28030. }
  28031. return this;
  28032. };
  28033. /**
  28034. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28035. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28036. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28037. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28038. * Returns the Mesh.
  28039. */
  28040. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28041. if (computeNormals === void 0) { computeNormals = true; }
  28042. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28043. if (!positions) {
  28044. return this;
  28045. }
  28046. positionFunction(positions);
  28047. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28048. if (computeNormals) {
  28049. var indices = this.getIndices();
  28050. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28051. if (!normals) {
  28052. return this;
  28053. }
  28054. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28055. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28056. }
  28057. return this;
  28058. };
  28059. /**
  28060. * Creates a un-shared specific occurence of the geometry for the mesh.
  28061. * Returns the Mesh.
  28062. */
  28063. Mesh.prototype.makeGeometryUnique = function () {
  28064. if (!this._geometry) {
  28065. return this;
  28066. }
  28067. var oldGeometry = this._geometry;
  28068. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28069. oldGeometry.releaseForMesh(this, true);
  28070. geometry.applyToMesh(this);
  28071. return this;
  28072. };
  28073. /**
  28074. * Sets the mesh indices.
  28075. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28076. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28077. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28078. * This method creates a new index buffer each call.
  28079. * Returns the Mesh.
  28080. */
  28081. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28082. if (totalVertices === void 0) { totalVertices = null; }
  28083. if (updatable === void 0) { updatable = false; }
  28084. if (!this._geometry) {
  28085. var vertexData = new BABYLON.VertexData();
  28086. vertexData.indices = indices;
  28087. var scene = this.getScene();
  28088. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28089. }
  28090. else {
  28091. this._geometry.setIndices(indices, totalVertices, updatable);
  28092. }
  28093. return this;
  28094. };
  28095. /**
  28096. * Update the current index buffer
  28097. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28098. * Returns the Mesh.
  28099. */
  28100. Mesh.prototype.updateIndices = function (indices, offset) {
  28101. if (!this._geometry) {
  28102. return this;
  28103. }
  28104. this._geometry.updateIndices(indices, offset);
  28105. return this;
  28106. };
  28107. /**
  28108. * Invert the geometry to move from a right handed system to a left handed one.
  28109. * Returns the Mesh.
  28110. */
  28111. Mesh.prototype.toLeftHanded = function () {
  28112. if (!this._geometry) {
  28113. return this;
  28114. }
  28115. this._geometry.toLeftHanded();
  28116. return this;
  28117. };
  28118. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28119. if (!this._geometry) {
  28120. return this;
  28121. }
  28122. var engine = this.getScene().getEngine();
  28123. // Wireframe
  28124. var indexToBind;
  28125. if (this._unIndexed) {
  28126. indexToBind = null;
  28127. }
  28128. else {
  28129. switch (fillMode) {
  28130. case BABYLON.Material.PointFillMode:
  28131. indexToBind = null;
  28132. break;
  28133. case BABYLON.Material.WireFrameFillMode:
  28134. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28135. break;
  28136. default:
  28137. case BABYLON.Material.TriangleFillMode:
  28138. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28139. break;
  28140. }
  28141. }
  28142. // VBOs
  28143. this._geometry._bind(effect, indexToBind);
  28144. return this;
  28145. };
  28146. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28147. if (alternate === void 0) { alternate = false; }
  28148. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28149. return this;
  28150. }
  28151. this.onBeforeDrawObservable.notifyObservers(this);
  28152. var scene = this.getScene();
  28153. var engine = scene.getEngine();
  28154. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28155. // or triangles as points
  28156. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28157. }
  28158. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28159. // Triangles as wireframe
  28160. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28161. }
  28162. else {
  28163. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28164. }
  28165. if (scene._isAlternateRenderingEnabled && !alternate) {
  28166. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28167. if (!effect || !scene.activeCamera) {
  28168. return this;
  28169. }
  28170. scene._switchToAlternateCameraConfiguration(true);
  28171. this._effectiveMaterial.bindView(effect);
  28172. this._effectiveMaterial.bindViewProjection(effect);
  28173. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28174. this._draw(subMesh, fillMode, instancesCount, true);
  28175. engine.setViewport(scene.activeCamera.viewport);
  28176. scene._switchToAlternateCameraConfiguration(false);
  28177. this._effectiveMaterial.bindView(effect);
  28178. this._effectiveMaterial.bindViewProjection(effect);
  28179. }
  28180. return this;
  28181. };
  28182. /**
  28183. * Registers for this mesh a javascript function called just before the rendering process.
  28184. * This function is passed the current mesh.
  28185. * Return the Mesh.
  28186. */
  28187. Mesh.prototype.registerBeforeRender = function (func) {
  28188. this.onBeforeRenderObservable.add(func);
  28189. return this;
  28190. };
  28191. /**
  28192. * Disposes a previously registered javascript function called before the rendering.
  28193. * This function is passed the current mesh.
  28194. * Returns the Mesh.
  28195. */
  28196. Mesh.prototype.unregisterBeforeRender = function (func) {
  28197. this.onBeforeRenderObservable.removeCallback(func);
  28198. return this;
  28199. };
  28200. /**
  28201. * Registers for this mesh a javascript function called just after the rendering is complete.
  28202. * This function is passed the current mesh.
  28203. * Returns the Mesh.
  28204. */
  28205. Mesh.prototype.registerAfterRender = function (func) {
  28206. this.onAfterRenderObservable.add(func);
  28207. return this;
  28208. };
  28209. /**
  28210. * Disposes a previously registered javascript function called after the rendering.
  28211. * This function is passed the current mesh.
  28212. * Return the Mesh.
  28213. */
  28214. Mesh.prototype.unregisterAfterRender = function (func) {
  28215. this.onAfterRenderObservable.removeCallback(func);
  28216. return this;
  28217. };
  28218. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28219. var scene = this.getScene();
  28220. this._batchCache.mustReturn = false;
  28221. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28222. this._batchCache.visibleInstances[subMeshId] = null;
  28223. if (this._visibleInstances) {
  28224. var currentRenderId = scene.getRenderId();
  28225. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28226. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28227. var selfRenderId = this._renderId;
  28228. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28229. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28230. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28231. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28232. }
  28233. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28234. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28235. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28236. this._batchCache.mustReturn = true;
  28237. return this._batchCache;
  28238. }
  28239. if (currentRenderId !== selfRenderId) {
  28240. this._batchCache.renderSelf[subMeshId] = false;
  28241. }
  28242. }
  28243. this._renderIdForInstances[subMeshId] = currentRenderId;
  28244. }
  28245. return this._batchCache;
  28246. };
  28247. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28248. var visibleInstances = batch.visibleInstances[subMesh._id];
  28249. if (!visibleInstances) {
  28250. return this;
  28251. }
  28252. var matricesCount = visibleInstances.length + 1;
  28253. var bufferSize = matricesCount * 16 * 4;
  28254. var currentInstancesBufferSize = this._instancesBufferSize;
  28255. var instancesBuffer = this._instancesBuffer;
  28256. while (this._instancesBufferSize < bufferSize) {
  28257. this._instancesBufferSize *= 2;
  28258. }
  28259. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28260. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28261. }
  28262. var offset = 0;
  28263. var instancesCount = 0;
  28264. var world = this.getWorldMatrix();
  28265. if (batch.renderSelf[subMesh._id]) {
  28266. world.copyToArray(this._instancesData, offset);
  28267. offset += 16;
  28268. instancesCount++;
  28269. }
  28270. if (visibleInstances) {
  28271. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28272. var instance = visibleInstances[instanceIndex];
  28273. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28274. offset += 16;
  28275. instancesCount++;
  28276. }
  28277. }
  28278. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28279. if (instancesBuffer) {
  28280. instancesBuffer.dispose();
  28281. }
  28282. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28283. this._instancesBuffer = instancesBuffer;
  28284. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28285. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28286. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28287. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28288. }
  28289. else {
  28290. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28291. }
  28292. this._bind(subMesh, effect, fillMode);
  28293. this._draw(subMesh, fillMode, instancesCount);
  28294. engine.unbindInstanceAttributes();
  28295. return this;
  28296. };
  28297. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28298. var scene = this.getScene();
  28299. var engine = scene.getEngine();
  28300. if (hardwareInstancedRendering) {
  28301. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28302. }
  28303. else {
  28304. if (batch.renderSelf[subMesh._id]) {
  28305. // Draw
  28306. if (onBeforeDraw) {
  28307. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28308. }
  28309. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28310. }
  28311. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28312. if (visibleInstancesForSubMesh) {
  28313. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28314. var instance = visibleInstancesForSubMesh[instanceIndex];
  28315. // World
  28316. var world = instance.getWorldMatrix();
  28317. if (onBeforeDraw) {
  28318. onBeforeDraw(true, world, effectiveMaterial);
  28319. }
  28320. // Draw
  28321. this._draw(subMesh, fillMode);
  28322. }
  28323. }
  28324. }
  28325. return this;
  28326. };
  28327. /**
  28328. * Triggers the draw call for the mesh.
  28329. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28330. * Returns the Mesh.
  28331. */
  28332. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28333. this.checkOcclusionQuery();
  28334. if (this._isOccluded) {
  28335. return this;
  28336. }
  28337. var scene = this.getScene();
  28338. // Managing instances
  28339. var batch = this._getInstancesRenderList(subMesh._id);
  28340. if (batch.mustReturn) {
  28341. return this;
  28342. }
  28343. // Checking geometry state
  28344. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28345. return this;
  28346. }
  28347. this.onBeforeRenderObservable.notifyObservers(this);
  28348. var engine = scene.getEngine();
  28349. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28350. // Material
  28351. var material = subMesh.getMaterial();
  28352. if (!material) {
  28353. return this;
  28354. }
  28355. this._effectiveMaterial = material;
  28356. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28357. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28358. return this;
  28359. }
  28360. }
  28361. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28362. return this;
  28363. }
  28364. // Alpha mode
  28365. if (enableAlphaMode) {
  28366. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28367. }
  28368. // Outline - step 1
  28369. var savedDepthWrite = engine.getDepthWrite();
  28370. if (this.renderOutline) {
  28371. engine.setDepthWrite(false);
  28372. scene.getOutlineRenderer().render(subMesh, batch);
  28373. engine.setDepthWrite(savedDepthWrite);
  28374. }
  28375. var effect;
  28376. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28377. effect = subMesh.effect;
  28378. }
  28379. else {
  28380. effect = this._effectiveMaterial.getEffect();
  28381. }
  28382. if (!effect) {
  28383. return this;
  28384. }
  28385. var sideOrientation = this.overrideMaterialSideOrientation;
  28386. if (sideOrientation == null) {
  28387. sideOrientation = this._effectiveMaterial.sideOrientation;
  28388. if (this._getWorldMatrixDeterminant() < 0) {
  28389. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28390. }
  28391. }
  28392. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28393. if (this._effectiveMaterial.forceDepthWrite) {
  28394. engine.setDepthWrite(true);
  28395. }
  28396. // Bind
  28397. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28398. if (!hardwareInstancedRendering) {
  28399. this._bind(subMesh, effect, fillMode);
  28400. }
  28401. var world = this.getWorldMatrix();
  28402. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28403. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28404. }
  28405. else {
  28406. this._effectiveMaterial.bind(world, this);
  28407. }
  28408. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28409. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28410. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28411. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28412. }
  28413. // Draw
  28414. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28415. // Unbind
  28416. this._effectiveMaterial.unbind();
  28417. // Outline - step 2
  28418. if (this.renderOutline && savedDepthWrite) {
  28419. engine.setDepthWrite(true);
  28420. engine.setColorWrite(false);
  28421. scene.getOutlineRenderer().render(subMesh, batch);
  28422. engine.setColorWrite(true);
  28423. }
  28424. // Overlay
  28425. if (this.renderOverlay) {
  28426. var currentMode = engine.getAlphaMode();
  28427. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28428. scene.getOutlineRenderer().render(subMesh, batch, true);
  28429. engine.setAlphaMode(currentMode);
  28430. }
  28431. this.onAfterRenderObservable.notifyObservers(this);
  28432. return this;
  28433. };
  28434. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28435. if (isInstance && effectiveMaterial) {
  28436. effectiveMaterial.bindOnlyWorldMatrix(world);
  28437. }
  28438. };
  28439. /**
  28440. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28441. */
  28442. Mesh.prototype.getEmittedParticleSystems = function () {
  28443. var results = new Array();
  28444. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28445. var particleSystem = this.getScene().particleSystems[index];
  28446. if (particleSystem.emitter === this) {
  28447. results.push(particleSystem);
  28448. }
  28449. }
  28450. return results;
  28451. };
  28452. /**
  28453. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28454. */
  28455. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28456. var results = new Array();
  28457. var descendants = this.getDescendants();
  28458. descendants.push(this);
  28459. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28460. var particleSystem = this.getScene().particleSystems[index];
  28461. var emitter = particleSystem.emitter;
  28462. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28463. results.push(particleSystem);
  28464. }
  28465. }
  28466. return results;
  28467. };
  28468. Mesh.prototype._checkDelayState = function () {
  28469. var scene = this.getScene();
  28470. if (this._geometry) {
  28471. this._geometry.load(scene);
  28472. }
  28473. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28475. this._queueLoad(scene);
  28476. }
  28477. return this;
  28478. };
  28479. Mesh.prototype._queueLoad = function (scene) {
  28480. var _this = this;
  28481. scene._addPendingData(this);
  28482. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28483. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28484. if (data instanceof ArrayBuffer) {
  28485. _this._delayLoadingFunction(data, _this);
  28486. }
  28487. else {
  28488. _this._delayLoadingFunction(JSON.parse(data), _this);
  28489. }
  28490. _this.instances.forEach(function (instance) {
  28491. instance._syncSubMeshes();
  28492. });
  28493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28494. scene._removePendingData(_this);
  28495. }, function () { }, scene.database, getBinaryData);
  28496. return this;
  28497. };
  28498. /**
  28499. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28500. */
  28501. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28502. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28503. return false;
  28504. }
  28505. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28506. return false;
  28507. }
  28508. this._checkDelayState();
  28509. return true;
  28510. };
  28511. /**
  28512. * Sets the mesh material by the material or multiMaterial `id` property.
  28513. * The material `id` is a string identifying the material or the multiMaterial.
  28514. * This method returns the Mesh.
  28515. */
  28516. Mesh.prototype.setMaterialByID = function (id) {
  28517. var materials = this.getScene().materials;
  28518. var index;
  28519. for (index = materials.length - 1; index > -1; index--) {
  28520. if (materials[index].id === id) {
  28521. this.material = materials[index];
  28522. return this;
  28523. }
  28524. }
  28525. // Multi
  28526. var multiMaterials = this.getScene().multiMaterials;
  28527. for (index = multiMaterials.length - 1; index > -1; index--) {
  28528. if (multiMaterials[index].id === id) {
  28529. this.material = multiMaterials[index];
  28530. return this;
  28531. }
  28532. }
  28533. return this;
  28534. };
  28535. /**
  28536. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28537. */
  28538. Mesh.prototype.getAnimatables = function () {
  28539. var results = new Array();
  28540. if (this.material) {
  28541. results.push(this.material);
  28542. }
  28543. if (this.skeleton) {
  28544. results.push(this.skeleton);
  28545. }
  28546. return results;
  28547. };
  28548. /**
  28549. * Modifies the mesh geometry according to the passed transformation matrix.
  28550. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28551. * The mesh normals are modified accordingly the same transformation.
  28552. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28553. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28554. * Returns the Mesh.
  28555. */
  28556. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28557. // Position
  28558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28559. return this;
  28560. }
  28561. var submeshes = this.subMeshes.splice(0);
  28562. this._resetPointsArrayCache();
  28563. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28564. var temp = new Array();
  28565. var index;
  28566. for (index = 0; index < data.length; index += 3) {
  28567. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28568. }
  28569. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28570. // Normals
  28571. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28572. return this;
  28573. }
  28574. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28575. temp = [];
  28576. for (index = 0; index < data.length; index += 3) {
  28577. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28578. }
  28579. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28580. // flip faces?
  28581. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28582. this.flipFaces();
  28583. }
  28584. // Restore submeshes
  28585. this.releaseSubMeshes();
  28586. this.subMeshes = submeshes;
  28587. return this;
  28588. };
  28589. /**
  28590. * Modifies the mesh geometry according to its own current World Matrix.
  28591. * The mesh World Matrix is then reset.
  28592. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28593. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28594. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28595. * Returns the Mesh.
  28596. */
  28597. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28598. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28599. this.scaling.copyFromFloats(1, 1, 1);
  28600. this.position.copyFromFloats(0, 0, 0);
  28601. this.rotation.copyFromFloats(0, 0, 0);
  28602. //only if quaternion is already set
  28603. if (this.rotationQuaternion) {
  28604. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28605. }
  28606. this._worldMatrix = BABYLON.Matrix.Identity();
  28607. return this;
  28608. };
  28609. Object.defineProperty(Mesh.prototype, "_positions", {
  28610. // Cache
  28611. get: function () {
  28612. if (this._geometry) {
  28613. return this._geometry._positions;
  28614. }
  28615. return null;
  28616. },
  28617. enumerable: true,
  28618. configurable: true
  28619. });
  28620. Mesh.prototype._resetPointsArrayCache = function () {
  28621. if (this._geometry) {
  28622. this._geometry._resetPointsArrayCache();
  28623. }
  28624. return this;
  28625. };
  28626. Mesh.prototype._generatePointsArray = function () {
  28627. if (this._geometry) {
  28628. return this._geometry._generatePointsArray();
  28629. }
  28630. return false;
  28631. };
  28632. /**
  28633. * Returns a new Mesh object generated from the current mesh properties.
  28634. * This method must not get confused with createInstance().
  28635. * The parameter `name` is a string, the name given to the new mesh.
  28636. * The optional parameter `newParent` can be any Node object (default `null`).
  28637. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28638. * 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.
  28639. */
  28640. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28641. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28642. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28643. };
  28644. /**
  28645. * Disposes the Mesh.
  28646. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28647. * Returns nothing.
  28648. */
  28649. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28650. var _this = this;
  28651. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28652. this.morphTargetManager = null;
  28653. if (this._geometry) {
  28654. this._geometry.releaseForMesh(this, true);
  28655. }
  28656. // Sources
  28657. var meshes = this.getScene().meshes;
  28658. meshes.forEach(function (abstractMesh) {
  28659. var mesh = abstractMesh;
  28660. if (mesh._source && mesh._source === _this) {
  28661. mesh._source = null;
  28662. }
  28663. });
  28664. this._source = null;
  28665. // Instances
  28666. if (this._instancesBuffer) {
  28667. this._instancesBuffer.dispose();
  28668. this._instancesBuffer = null;
  28669. }
  28670. while (this.instances.length) {
  28671. this.instances[0].dispose();
  28672. }
  28673. // Effect layers.
  28674. var effectLayers = this.getScene().effectLayers;
  28675. for (var i = 0; i < effectLayers.length; i++) {
  28676. var effectLayer = effectLayers[i];
  28677. if (effectLayer) {
  28678. effectLayer._disposeMesh(this);
  28679. }
  28680. }
  28681. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28682. };
  28683. /**
  28684. * Modifies the mesh geometry according to a displacement map.
  28685. * 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.
  28686. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28687. * This method returns nothing.
  28688. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28689. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28690. * 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.
  28691. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28692. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28693. *
  28694. * Returns the Mesh.
  28695. */
  28696. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28697. var _this = this;
  28698. var scene = this.getScene();
  28699. var onload = function (img) {
  28700. // Getting height map data
  28701. var canvas = document.createElement("canvas");
  28702. var context = canvas.getContext("2d");
  28703. var heightMapWidth = img.width;
  28704. var heightMapHeight = img.height;
  28705. canvas.width = heightMapWidth;
  28706. canvas.height = heightMapHeight;
  28707. context.drawImage(img, 0, 0);
  28708. // Create VertexData from map data
  28709. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28710. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28711. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28712. //execute success callback, if set
  28713. if (onSuccess) {
  28714. onSuccess(_this);
  28715. }
  28716. };
  28717. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28718. return this;
  28719. };
  28720. /**
  28721. * Modifies the mesh geometry according to a displacementMap buffer.
  28722. * 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.
  28723. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28724. * This method returns nothing.
  28725. * 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.
  28726. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28727. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28728. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28729. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28730. *
  28731. * Returns the Mesh.
  28732. */
  28733. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28734. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28735. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28736. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28737. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28738. return this;
  28739. }
  28740. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28741. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28742. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28743. var position = BABYLON.Vector3.Zero();
  28744. var normal = BABYLON.Vector3.Zero();
  28745. var uv = BABYLON.Vector2.Zero();
  28746. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28747. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28748. for (var index = 0; index < positions.length; index += 3) {
  28749. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28750. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28751. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28752. // Compute height
  28753. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28754. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28755. var pos = (u + v * heightMapWidth) * 4;
  28756. var r = buffer[pos] / 255.0;
  28757. var g = buffer[pos + 1] / 255.0;
  28758. var b = buffer[pos + 2] / 255.0;
  28759. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28760. normal.normalize();
  28761. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28762. position = position.add(normal);
  28763. position.toArray(positions, index);
  28764. }
  28765. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28766. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28767. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28768. return this;
  28769. };
  28770. /**
  28771. * Modify the mesh to get a flat shading rendering.
  28772. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28773. * This method returns the Mesh.
  28774. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28775. */
  28776. Mesh.prototype.convertToFlatShadedMesh = function () {
  28777. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28778. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28779. var kinds = this.getVerticesDataKinds();
  28780. var vbs = {};
  28781. var data = {};
  28782. var newdata = {};
  28783. var updatableNormals = false;
  28784. var kindIndex;
  28785. var kind;
  28786. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28787. kind = kinds[kindIndex];
  28788. var vertexBuffer = this.getVertexBuffer(kind);
  28789. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28790. updatableNormals = vertexBuffer.isUpdatable();
  28791. kinds.splice(kindIndex, 1);
  28792. kindIndex--;
  28793. continue;
  28794. }
  28795. vbs[kind] = vertexBuffer;
  28796. data[kind] = vbs[kind].getData();
  28797. newdata[kind] = [];
  28798. }
  28799. // Save previous submeshes
  28800. var previousSubmeshes = this.subMeshes.slice(0);
  28801. var indices = this.getIndices();
  28802. var totalIndices = this.getTotalIndices();
  28803. // Generating unique vertices per face
  28804. var index;
  28805. for (index = 0; index < totalIndices; index++) {
  28806. var vertexIndex = indices[index];
  28807. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28808. kind = kinds[kindIndex];
  28809. var stride = vbs[kind].getStrideSize();
  28810. for (var offset = 0; offset < stride; offset++) {
  28811. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28812. }
  28813. }
  28814. }
  28815. // Updating faces & normal
  28816. var normals = [];
  28817. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28818. for (index = 0; index < totalIndices; index += 3) {
  28819. indices[index] = index;
  28820. indices[index + 1] = index + 1;
  28821. indices[index + 2] = index + 2;
  28822. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28823. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28824. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28825. var p1p2 = p1.subtract(p2);
  28826. var p3p2 = p3.subtract(p2);
  28827. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28828. // Store same normals for every vertex
  28829. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28830. normals.push(normal.x);
  28831. normals.push(normal.y);
  28832. normals.push(normal.z);
  28833. }
  28834. }
  28835. this.setIndices(indices);
  28836. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28837. // Updating vertex buffers
  28838. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28839. kind = kinds[kindIndex];
  28840. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28841. }
  28842. // Updating submeshes
  28843. this.releaseSubMeshes();
  28844. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28845. var previousOne = previousSubmeshes[submeshIndex];
  28846. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28847. }
  28848. this.synchronizeInstances();
  28849. return this;
  28850. };
  28851. /**
  28852. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28853. * In other words, more vertices, no more indices and a single bigger VBO.
  28854. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28855. * Returns the Mesh.
  28856. */
  28857. Mesh.prototype.convertToUnIndexedMesh = function () {
  28858. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28859. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28860. var kinds = this.getVerticesDataKinds();
  28861. var vbs = {};
  28862. var data = {};
  28863. var newdata = {};
  28864. var kindIndex;
  28865. var kind;
  28866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28867. kind = kinds[kindIndex];
  28868. var vertexBuffer = this.getVertexBuffer(kind);
  28869. vbs[kind] = vertexBuffer;
  28870. data[kind] = vbs[kind].getData();
  28871. newdata[kind] = [];
  28872. }
  28873. // Save previous submeshes
  28874. var previousSubmeshes = this.subMeshes.slice(0);
  28875. var indices = this.getIndices();
  28876. var totalIndices = this.getTotalIndices();
  28877. // Generating unique vertices per face
  28878. var index;
  28879. for (index = 0; index < totalIndices; index++) {
  28880. var vertexIndex = indices[index];
  28881. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28882. kind = kinds[kindIndex];
  28883. var stride = vbs[kind].getStrideSize();
  28884. for (var offset = 0; offset < stride; offset++) {
  28885. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28886. }
  28887. }
  28888. }
  28889. // Updating indices
  28890. for (index = 0; index < totalIndices; index += 3) {
  28891. indices[index] = index;
  28892. indices[index + 1] = index + 1;
  28893. indices[index + 2] = index + 2;
  28894. }
  28895. this.setIndices(indices);
  28896. // Updating vertex buffers
  28897. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28898. kind = kinds[kindIndex];
  28899. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28900. }
  28901. // Updating submeshes
  28902. this.releaseSubMeshes();
  28903. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28904. var previousOne = previousSubmeshes[submeshIndex];
  28905. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28906. }
  28907. this._unIndexed = true;
  28908. this.synchronizeInstances();
  28909. return this;
  28910. };
  28911. /**
  28912. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28913. * This method returns the Mesh.
  28914. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28915. */
  28916. Mesh.prototype.flipFaces = function (flipNormals) {
  28917. if (flipNormals === void 0) { flipNormals = false; }
  28918. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28919. var i;
  28920. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28921. for (i = 0; i < vertex_data.normals.length; i++) {
  28922. vertex_data.normals[i] *= -1;
  28923. }
  28924. }
  28925. if (vertex_data.indices) {
  28926. var temp;
  28927. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28928. // reassign indices
  28929. temp = vertex_data.indices[i + 1];
  28930. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28931. vertex_data.indices[i + 2] = temp;
  28932. }
  28933. }
  28934. vertex_data.applyToMesh(this);
  28935. return this;
  28936. };
  28937. // Instances
  28938. /**
  28939. * Creates a new InstancedMesh object from the mesh model.
  28940. * An instance shares the same properties and the same material than its model.
  28941. * Only these properties of each instance can then be set individually :
  28942. * - position
  28943. * - rotation
  28944. * - rotationQuaternion
  28945. * - setPivotMatrix
  28946. * - scaling
  28947. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28948. * Warning : this method is not supported for Line mesh and LineSystem
  28949. */
  28950. Mesh.prototype.createInstance = function (name) {
  28951. return new BABYLON.InstancedMesh(name, this);
  28952. };
  28953. /**
  28954. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28955. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28956. * This method returns the Mesh.
  28957. */
  28958. Mesh.prototype.synchronizeInstances = function () {
  28959. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28960. var instance = this.instances[instanceIndex];
  28961. instance._syncSubMeshes();
  28962. }
  28963. return this;
  28964. };
  28965. /**
  28966. * Simplify the mesh according to the given array of settings.
  28967. * Function will return immediately and will simplify async. It returns the Mesh.
  28968. * @param settings a collection of simplification settings.
  28969. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28970. * @param type the type of simplification to run.
  28971. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28972. */
  28973. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28974. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28975. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28976. this.getScene().simplificationQueue.addTask({
  28977. settings: settings,
  28978. parallelProcessing: parallelProcessing,
  28979. mesh: this,
  28980. simplificationType: simplificationType,
  28981. successCallback: successCallback
  28982. });
  28983. return this;
  28984. };
  28985. /**
  28986. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28987. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28988. * This should be used together with the simplification to avoid disappearing triangles.
  28989. * Returns the Mesh.
  28990. * @param successCallback an optional success callback to be called after the optimization finished.
  28991. */
  28992. Mesh.prototype.optimizeIndices = function (successCallback) {
  28993. var _this = this;
  28994. var indices = this.getIndices();
  28995. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28996. if (!positions || !indices) {
  28997. return this;
  28998. }
  28999. var vectorPositions = new Array();
  29000. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29001. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29002. }
  29003. var dupes = new Array();
  29004. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29005. var realPos = vectorPositions.length - 1 - iteration;
  29006. var testedPosition = vectorPositions[realPos];
  29007. for (var j = 0; j < realPos; ++j) {
  29008. var againstPosition = vectorPositions[j];
  29009. if (testedPosition.equals(againstPosition)) {
  29010. dupes[realPos] = j;
  29011. break;
  29012. }
  29013. }
  29014. }, function () {
  29015. for (var i = 0; i < indices.length; ++i) {
  29016. indices[i] = dupes[indices[i]] || indices[i];
  29017. }
  29018. //indices are now reordered
  29019. var originalSubMeshes = _this.subMeshes.slice(0);
  29020. _this.setIndices(indices);
  29021. _this.subMeshes = originalSubMeshes;
  29022. if (successCallback) {
  29023. successCallback(_this);
  29024. }
  29025. });
  29026. return this;
  29027. };
  29028. Mesh.prototype.serialize = function (serializationObject) {
  29029. serializationObject.name = this.name;
  29030. serializationObject.id = this.id;
  29031. serializationObject.type = this.getClassName();
  29032. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29033. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29034. }
  29035. serializationObject.position = this.position.asArray();
  29036. if (this.rotationQuaternion) {
  29037. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29038. }
  29039. else if (this.rotation) {
  29040. serializationObject.rotation = this.rotation.asArray();
  29041. }
  29042. serializationObject.scaling = this.scaling.asArray();
  29043. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29044. serializationObject.isEnabled = this.isEnabled(false);
  29045. serializationObject.isVisible = this.isVisible;
  29046. serializationObject.infiniteDistance = this.infiniteDistance;
  29047. serializationObject.pickable = this.isPickable;
  29048. serializationObject.receiveShadows = this.receiveShadows;
  29049. serializationObject.billboardMode = this.billboardMode;
  29050. serializationObject.visibility = this.visibility;
  29051. serializationObject.checkCollisions = this.checkCollisions;
  29052. serializationObject.isBlocker = this.isBlocker;
  29053. // Parent
  29054. if (this.parent) {
  29055. serializationObject.parentId = this.parent.id;
  29056. }
  29057. // Geometry
  29058. serializationObject.isUnIndexed = this.isUnIndexed;
  29059. var geometry = this._geometry;
  29060. if (geometry) {
  29061. var geometryId = geometry.id;
  29062. serializationObject.geometryId = geometryId;
  29063. // SubMeshes
  29064. serializationObject.subMeshes = [];
  29065. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29066. var subMesh = this.subMeshes[subIndex];
  29067. serializationObject.subMeshes.push({
  29068. materialIndex: subMesh.materialIndex,
  29069. verticesStart: subMesh.verticesStart,
  29070. verticesCount: subMesh.verticesCount,
  29071. indexStart: subMesh.indexStart,
  29072. indexCount: subMesh.indexCount
  29073. });
  29074. }
  29075. }
  29076. // Material
  29077. if (this.material) {
  29078. serializationObject.materialId = this.material.id;
  29079. }
  29080. else {
  29081. this.material = null;
  29082. }
  29083. // Morph targets
  29084. if (this.morphTargetManager) {
  29085. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29086. }
  29087. // Skeleton
  29088. if (this.skeleton) {
  29089. serializationObject.skeletonId = this.skeleton.id;
  29090. }
  29091. // Physics
  29092. //TODO implement correct serialization for physics impostors.
  29093. var impostor = this.getPhysicsImpostor();
  29094. if (impostor) {
  29095. serializationObject.physicsMass = impostor.getParam("mass");
  29096. serializationObject.physicsFriction = impostor.getParam("friction");
  29097. serializationObject.physicsRestitution = impostor.getParam("mass");
  29098. serializationObject.physicsImpostor = impostor.type;
  29099. }
  29100. // Metadata
  29101. if (this.metadata) {
  29102. serializationObject.metadata = this.metadata;
  29103. }
  29104. // Instances
  29105. serializationObject.instances = [];
  29106. for (var index = 0; index < this.instances.length; index++) {
  29107. var instance = this.instances[index];
  29108. var serializationInstance = {
  29109. name: instance.name,
  29110. id: instance.id,
  29111. position: instance.position.asArray(),
  29112. scaling: instance.scaling.asArray()
  29113. };
  29114. if (instance.rotationQuaternion) {
  29115. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29116. }
  29117. else if (instance.rotation) {
  29118. serializationInstance.rotation = instance.rotation.asArray();
  29119. }
  29120. serializationObject.instances.push(serializationInstance);
  29121. // Animations
  29122. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29123. serializationInstance.ranges = instance.serializeAnimationRanges();
  29124. }
  29125. //
  29126. // Animations
  29127. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29128. serializationObject.ranges = this.serializeAnimationRanges();
  29129. // Layer mask
  29130. serializationObject.layerMask = this.layerMask;
  29131. // Alpha
  29132. serializationObject.alphaIndex = this.alphaIndex;
  29133. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29134. // Overlay
  29135. serializationObject.overlayAlpha = this.overlayAlpha;
  29136. serializationObject.overlayColor = this.overlayColor.asArray();
  29137. serializationObject.renderOverlay = this.renderOverlay;
  29138. // Fog
  29139. serializationObject.applyFog = this.applyFog;
  29140. // Action Manager
  29141. if (this.actionManager) {
  29142. serializationObject.actions = this.actionManager.serialize(this.name);
  29143. }
  29144. };
  29145. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29146. if (!this.geometry) {
  29147. return;
  29148. }
  29149. this._markSubMeshesAsAttributesDirty();
  29150. var morphTargetManager = this._morphTargetManager;
  29151. if (morphTargetManager && morphTargetManager.vertexCount) {
  29152. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29153. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29154. this.morphTargetManager = null;
  29155. return;
  29156. }
  29157. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29158. var morphTarget = morphTargetManager.getActiveTarget(index);
  29159. var positions = morphTarget.getPositions();
  29160. if (!positions) {
  29161. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29162. return;
  29163. }
  29164. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29165. var normals = morphTarget.getNormals();
  29166. if (normals) {
  29167. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29168. }
  29169. var tangents = morphTarget.getTangents();
  29170. if (tangents) {
  29171. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29172. }
  29173. }
  29174. }
  29175. else {
  29176. var index = 0;
  29177. // Positions
  29178. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29179. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29180. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29181. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29182. }
  29183. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29184. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29185. }
  29186. index++;
  29187. }
  29188. }
  29189. };
  29190. // Statics
  29191. /**
  29192. * Returns a new Mesh object parsed from the source provided.
  29193. * The parameter `parsedMesh` is the source.
  29194. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29195. */
  29196. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29197. var mesh;
  29198. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29199. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29200. }
  29201. else {
  29202. mesh = new Mesh(parsedMesh.name, scene);
  29203. }
  29204. mesh.id = parsedMesh.id;
  29205. if (BABYLON.Tags) {
  29206. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29207. }
  29208. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29209. if (parsedMesh.metadata !== undefined) {
  29210. mesh.metadata = parsedMesh.metadata;
  29211. }
  29212. if (parsedMesh.rotationQuaternion) {
  29213. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29214. }
  29215. else if (parsedMesh.rotation) {
  29216. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29217. }
  29218. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29219. if (parsedMesh.localMatrix) {
  29220. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29221. }
  29222. else if (parsedMesh.pivotMatrix) {
  29223. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29224. }
  29225. mesh.setEnabled(parsedMesh.isEnabled);
  29226. mesh.isVisible = parsedMesh.isVisible;
  29227. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29228. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29229. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29230. if (parsedMesh.applyFog !== undefined) {
  29231. mesh.applyFog = parsedMesh.applyFog;
  29232. }
  29233. if (parsedMesh.pickable !== undefined) {
  29234. mesh.isPickable = parsedMesh.pickable;
  29235. }
  29236. if (parsedMesh.alphaIndex !== undefined) {
  29237. mesh.alphaIndex = parsedMesh.alphaIndex;
  29238. }
  29239. mesh.receiveShadows = parsedMesh.receiveShadows;
  29240. mesh.billboardMode = parsedMesh.billboardMode;
  29241. if (parsedMesh.visibility !== undefined) {
  29242. mesh.visibility = parsedMesh.visibility;
  29243. }
  29244. mesh.checkCollisions = parsedMesh.checkCollisions;
  29245. if (parsedMesh.isBlocker !== undefined) {
  29246. mesh.isBlocker = parsedMesh.isBlocker;
  29247. }
  29248. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29249. // freezeWorldMatrix
  29250. if (parsedMesh.freezeWorldMatrix) {
  29251. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29252. }
  29253. // Parent
  29254. if (parsedMesh.parentId) {
  29255. mesh._waitingParentId = parsedMesh.parentId;
  29256. }
  29257. // Actions
  29258. if (parsedMesh.actions !== undefined) {
  29259. mesh._waitingActions = parsedMesh.actions;
  29260. }
  29261. // Overlay
  29262. if (parsedMesh.overlayAlpha !== undefined) {
  29263. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29264. }
  29265. if (parsedMesh.overlayColor !== undefined) {
  29266. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29267. }
  29268. if (parsedMesh.renderOverlay !== undefined) {
  29269. mesh.renderOverlay = parsedMesh.renderOverlay;
  29270. }
  29271. // Geometry
  29272. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29273. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29274. if (parsedMesh.delayLoadingFile) {
  29275. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29276. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29277. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29278. if (parsedMesh._binaryInfo) {
  29279. mesh._binaryInfo = parsedMesh._binaryInfo;
  29280. }
  29281. mesh._delayInfo = [];
  29282. if (parsedMesh.hasUVs) {
  29283. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29284. }
  29285. if (parsedMesh.hasUVs2) {
  29286. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29287. }
  29288. if (parsedMesh.hasUVs3) {
  29289. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29290. }
  29291. if (parsedMesh.hasUVs4) {
  29292. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29293. }
  29294. if (parsedMesh.hasUVs5) {
  29295. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29296. }
  29297. if (parsedMesh.hasUVs6) {
  29298. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29299. }
  29300. if (parsedMesh.hasColors) {
  29301. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29302. }
  29303. if (parsedMesh.hasMatricesIndices) {
  29304. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29305. }
  29306. if (parsedMesh.hasMatricesWeights) {
  29307. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29308. }
  29309. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29310. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29311. mesh._checkDelayState();
  29312. }
  29313. }
  29314. else {
  29315. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29316. }
  29317. // Material
  29318. if (parsedMesh.materialId) {
  29319. mesh.setMaterialByID(parsedMesh.materialId);
  29320. }
  29321. else {
  29322. mesh.material = null;
  29323. }
  29324. // Morph targets
  29325. if (parsedMesh.morphTargetManagerId > -1) {
  29326. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29327. }
  29328. // Skeleton
  29329. if (parsedMesh.skeletonId > -1) {
  29330. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29331. if (parsedMesh.numBoneInfluencers) {
  29332. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29333. }
  29334. }
  29335. // Animations
  29336. if (parsedMesh.animations) {
  29337. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29338. var parsedAnimation = parsedMesh.animations[animationIndex];
  29339. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29340. }
  29341. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29342. }
  29343. if (parsedMesh.autoAnimate) {
  29344. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29345. }
  29346. // Layer Mask
  29347. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29348. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29349. }
  29350. else {
  29351. mesh.layerMask = 0x0FFFFFFF;
  29352. }
  29353. // Physics
  29354. if (parsedMesh.physicsImpostor) {
  29355. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29356. mass: parsedMesh.physicsMass,
  29357. friction: parsedMesh.physicsFriction,
  29358. restitution: parsedMesh.physicsRestitution
  29359. }, scene);
  29360. }
  29361. // Instances
  29362. if (parsedMesh.instances) {
  29363. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29364. var parsedInstance = parsedMesh.instances[index];
  29365. var instance = mesh.createInstance(parsedInstance.name);
  29366. if (parsedInstance.id) {
  29367. instance.id = parsedInstance.id;
  29368. }
  29369. if (BABYLON.Tags) {
  29370. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29371. }
  29372. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29373. if (parsedInstance.parentId) {
  29374. instance._waitingParentId = parsedInstance.parentId;
  29375. }
  29376. if (parsedInstance.rotationQuaternion) {
  29377. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29378. }
  29379. else if (parsedInstance.rotation) {
  29380. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29381. }
  29382. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29383. instance.checkCollisions = mesh.checkCollisions;
  29384. if (parsedMesh.animations) {
  29385. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29386. parsedAnimation = parsedMesh.animations[animationIndex];
  29387. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29388. }
  29389. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29390. }
  29391. }
  29392. }
  29393. return mesh;
  29394. };
  29395. /**
  29396. * Creates a ribbon mesh.
  29397. * Please consider using the same method from the MeshBuilder class instead.
  29398. * 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.
  29399. *
  29400. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29401. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29402. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29403. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29404. * 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.
  29405. * 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.
  29406. * 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
  29407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29410. */
  29411. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29412. if (closeArray === void 0) { closeArray = false; }
  29413. if (updatable === void 0) { updatable = false; }
  29414. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29415. pathArray: pathArray,
  29416. closeArray: closeArray,
  29417. closePath: closePath,
  29418. offset: offset,
  29419. updatable: updatable,
  29420. sideOrientation: sideOrientation,
  29421. instance: instance
  29422. }, scene);
  29423. };
  29424. /**
  29425. * Creates a plane polygonal mesh. By default, this is a disc.
  29426. * Please consider using the same method from the MeshBuilder class instead.
  29427. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29428. * 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.
  29429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29432. */
  29433. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29434. if (scene === void 0) { scene = null; }
  29435. var options = {
  29436. radius: radius,
  29437. tessellation: tessellation,
  29438. sideOrientation: sideOrientation,
  29439. updatable: updatable
  29440. };
  29441. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29442. };
  29443. /**
  29444. * Creates a box mesh.
  29445. * Please consider using the same method from the MeshBuilder class instead.
  29446. * The parameter `size` sets the size (float) of each box side (default 1).
  29447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29450. */
  29451. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29452. if (scene === void 0) { scene = null; }
  29453. var options = {
  29454. size: size,
  29455. sideOrientation: sideOrientation,
  29456. updatable: updatable
  29457. };
  29458. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29459. };
  29460. /**
  29461. * Creates a sphere mesh.
  29462. * Please consider using the same method from the MeshBuilder class instead.
  29463. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29464. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29468. */
  29469. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29470. var options = {
  29471. segments: segments,
  29472. diameterX: diameter,
  29473. diameterY: diameter,
  29474. diameterZ: diameter,
  29475. sideOrientation: sideOrientation,
  29476. updatable: updatable
  29477. };
  29478. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29479. };
  29480. /**
  29481. * Creates a cylinder or a cone mesh.
  29482. * Please consider using the same method from the MeshBuilder class instead.
  29483. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29484. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29485. * 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.
  29486. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29487. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29489. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29491. */
  29492. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29493. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29494. if (scene !== undefined) {
  29495. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29496. updatable = scene;
  29497. }
  29498. scene = subdivisions;
  29499. subdivisions = 1;
  29500. }
  29501. var options = {
  29502. height: height,
  29503. diameterTop: diameterTop,
  29504. diameterBottom: diameterBottom,
  29505. tessellation: tessellation,
  29506. subdivisions: subdivisions,
  29507. sideOrientation: sideOrientation,
  29508. updatable: updatable
  29509. };
  29510. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29511. };
  29512. // Torus (Code from SharpDX.org)
  29513. /**
  29514. * Creates a torus mesh.
  29515. * Please consider using the same method from the MeshBuilder class instead.
  29516. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29517. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29518. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29522. */
  29523. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29524. var options = {
  29525. diameter: diameter,
  29526. thickness: thickness,
  29527. tessellation: tessellation,
  29528. sideOrientation: sideOrientation,
  29529. updatable: updatable
  29530. };
  29531. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29532. };
  29533. /**
  29534. * Creates a torus knot mesh.
  29535. * Please consider using the same method from the MeshBuilder class instead.
  29536. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29537. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29538. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29539. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29540. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29543. */
  29544. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29545. var options = {
  29546. radius: radius,
  29547. tube: tube,
  29548. radialSegments: radialSegments,
  29549. tubularSegments: tubularSegments,
  29550. p: p,
  29551. q: q,
  29552. sideOrientation: sideOrientation,
  29553. updatable: updatable
  29554. };
  29555. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29556. };
  29557. /**
  29558. * Creates a line mesh.
  29559. * Please consider using the same method from the MeshBuilder class instead.
  29560. * 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.
  29561. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29562. * The parameter `points` is an array successive Vector3.
  29563. * 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
  29564. * When updating an instance, remember that only point positions can change, not the number of points.
  29565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29566. */
  29567. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29568. if (scene === void 0) { scene = null; }
  29569. if (updatable === void 0) { updatable = false; }
  29570. if (instance === void 0) { instance = null; }
  29571. var options = {
  29572. points: points,
  29573. updatable: updatable,
  29574. instance: instance
  29575. };
  29576. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29577. };
  29578. /**
  29579. * Creates a dashed line mesh.
  29580. * Please consider using the same method from the MeshBuilder class instead.
  29581. * 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.
  29582. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29583. * The parameter `points` is an array successive Vector3.
  29584. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29585. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29586. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29587. * 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
  29588. * When updating an instance, remember that only point positions can change, not the number of points.
  29589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29590. */
  29591. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29592. if (scene === void 0) { scene = null; }
  29593. var options = {
  29594. points: points,
  29595. dashSize: dashSize,
  29596. gapSize: gapSize,
  29597. dashNb: dashNb,
  29598. updatable: updatable,
  29599. instance: instance
  29600. };
  29601. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29602. };
  29603. /**
  29604. * Creates a polygon mesh.
  29605. * Please consider using the same method from the MeshBuilder class instead.
  29606. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29607. * 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.
  29608. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29610. * Remember you can only change the shape positions, not their number when updating a polygon.
  29611. */
  29612. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29613. var options = {
  29614. shape: shape,
  29615. holes: holes,
  29616. updatable: updatable,
  29617. sideOrientation: sideOrientation
  29618. };
  29619. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29620. };
  29621. /**
  29622. * Creates an extruded polygon mesh, with depth in the Y direction.
  29623. * Please consider using the same method from the MeshBuilder class instead.
  29624. */
  29625. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29626. var options = {
  29627. shape: shape,
  29628. holes: holes,
  29629. depth: depth,
  29630. updatable: updatable,
  29631. sideOrientation: sideOrientation
  29632. };
  29633. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates an extruded shape mesh.
  29637. * 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.
  29638. * Please consider using the same method from the MeshBuilder class instead.
  29639. *
  29640. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29641. * 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
  29642. * extruded along the Z axis.
  29643. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29644. * 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.
  29645. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29646. * 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
  29647. * 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
  29648. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29652. */
  29653. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29654. if (scene === void 0) { scene = null; }
  29655. var options = {
  29656. shape: shape,
  29657. path: path,
  29658. scale: scale,
  29659. rotation: rotation,
  29660. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29661. sideOrientation: sideOrientation,
  29662. instance: instance,
  29663. updatable: updatable
  29664. };
  29665. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29666. };
  29667. /**
  29668. * Creates an custom extruded shape mesh.
  29669. * 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.
  29670. * Please consider using the same method from the MeshBuilder class instead.
  29671. *
  29672. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29673. * 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
  29674. * extruded along the Z axis.
  29675. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29676. * 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
  29677. * and the distance of this point from the begining of the path :
  29678. * ```javascript
  29679. * var rotationFunction = function(i, distance) {
  29680. * // do things
  29681. * return rotationValue; }
  29682. * ```
  29683. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29684. * 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
  29685. * and the distance of this point from the begining of the path :
  29686. * ```javascript
  29687. * var scaleFunction = function(i, distance) {
  29688. * // do things
  29689. * return scaleValue;}
  29690. * ```
  29691. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29692. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29693. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29694. * 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
  29695. * 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
  29696. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29697. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29700. */
  29701. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29702. var options = {
  29703. shape: shape,
  29704. path: path,
  29705. scaleFunction: scaleFunction,
  29706. rotationFunction: rotationFunction,
  29707. ribbonCloseArray: ribbonCloseArray,
  29708. ribbonClosePath: ribbonClosePath,
  29709. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29710. sideOrientation: sideOrientation,
  29711. instance: instance,
  29712. updatable: updatable
  29713. };
  29714. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29715. };
  29716. /**
  29717. * Creates lathe mesh.
  29718. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29719. * Please consider using the same method from the MeshBuilder class instead.
  29720. * 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
  29721. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29722. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29723. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29725. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29727. */
  29728. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29729. var options = {
  29730. shape: shape,
  29731. radius: radius,
  29732. tessellation: tessellation,
  29733. sideOrientation: sideOrientation,
  29734. updatable: updatable
  29735. };
  29736. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29737. };
  29738. /**
  29739. * Creates a plane mesh.
  29740. * Please consider using the same method from the MeshBuilder class instead.
  29741. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29742. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29745. */
  29746. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29747. var options = {
  29748. size: size,
  29749. width: size,
  29750. height: size,
  29751. sideOrientation: sideOrientation,
  29752. updatable: updatable
  29753. };
  29754. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29755. };
  29756. /**
  29757. * Creates a ground mesh.
  29758. * Please consider using the same method from the MeshBuilder class instead.
  29759. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29760. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29762. */
  29763. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29764. var options = {
  29765. width: width,
  29766. height: height,
  29767. subdivisions: subdivisions,
  29768. updatable: updatable
  29769. };
  29770. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29771. };
  29772. /**
  29773. * Creates a tiled ground mesh.
  29774. * Please consider using the same method from the MeshBuilder class instead.
  29775. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29776. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29777. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29778. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29779. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29780. * numbers of subdivisions on the ground width and height of each tile.
  29781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29782. */
  29783. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29784. var options = {
  29785. xmin: xmin,
  29786. zmin: zmin,
  29787. xmax: xmax,
  29788. zmax: zmax,
  29789. subdivisions: subdivisions,
  29790. precision: precision,
  29791. updatable: updatable
  29792. };
  29793. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29794. };
  29795. /**
  29796. * Creates a ground mesh from a height map.
  29797. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29798. * Please consider using the same method from the MeshBuilder class instead.
  29799. * The parameter `url` sets the URL of the height map image resource.
  29800. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29801. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29802. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29803. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29804. * 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).
  29805. * This function is passed the newly built mesh :
  29806. * ```javascript
  29807. * function(mesh) { // do things
  29808. * return; }
  29809. * ```
  29810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29811. */
  29812. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29813. var options = {
  29814. width: width,
  29815. height: height,
  29816. subdivisions: subdivisions,
  29817. minHeight: minHeight,
  29818. maxHeight: maxHeight,
  29819. updatable: updatable,
  29820. onReady: onReady
  29821. };
  29822. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29823. };
  29824. /**
  29825. * Creates a tube mesh.
  29826. * 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.
  29827. * Please consider using the same method from the MeshBuilder class instead.
  29828. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29829. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29830. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29831. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29832. * 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.
  29833. * It must return a radius value (positive float) :
  29834. * ```javascript
  29835. * var radiusFunction = function(i, distance) {
  29836. * // do things
  29837. * return radius; }
  29838. * ```
  29839. * 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
  29840. * 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
  29841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29844. */
  29845. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29846. var options = {
  29847. path: path,
  29848. radius: radius,
  29849. tessellation: tessellation,
  29850. radiusFunction: radiusFunction,
  29851. arc: 1,
  29852. cap: cap,
  29853. updatable: updatable,
  29854. sideOrientation: sideOrientation,
  29855. instance: instance
  29856. };
  29857. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29858. };
  29859. /**
  29860. * Creates a polyhedron mesh.
  29861. * Please consider using the same method from the MeshBuilder class instead.
  29862. * 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
  29863. * to choose the wanted type.
  29864. * The parameter `size` (positive float, default 1) sets the polygon size.
  29865. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29866. * 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`.
  29867. * 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
  29868. * 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)`).
  29869. * 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
  29870. * 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.
  29871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29874. */
  29875. Mesh.CreatePolyhedron = function (name, options, scene) {
  29876. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29877. };
  29878. /**
  29879. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29880. * Please consider using the same method from the MeshBuilder class instead.
  29881. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29882. * 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`).
  29883. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29884. * 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.
  29885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29888. */
  29889. Mesh.CreateIcoSphere = function (name, options, scene) {
  29890. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29891. };
  29892. /**
  29893. * Creates a decal mesh.
  29894. * Please consider using the same method from the MeshBuilder class instead.
  29895. * 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.
  29896. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29897. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29898. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29899. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29900. */
  29901. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29902. var options = {
  29903. position: position,
  29904. normal: normal,
  29905. size: size,
  29906. angle: angle
  29907. };
  29908. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29909. };
  29910. // Skeletons
  29911. /**
  29912. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29913. */
  29914. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29915. if (!this._sourcePositions) {
  29916. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29917. if (!source) {
  29918. return this._sourcePositions;
  29919. }
  29920. this._sourcePositions = new Float32Array(source);
  29921. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29922. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29923. }
  29924. }
  29925. return this._sourcePositions;
  29926. };
  29927. /**
  29928. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29929. */
  29930. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29931. if (!this._sourceNormals) {
  29932. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29933. if (!source) {
  29934. return this._sourceNormals;
  29935. }
  29936. this._sourceNormals = new Float32Array(source);
  29937. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29938. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29939. }
  29940. }
  29941. return this._sourceNormals;
  29942. };
  29943. /**
  29944. * Updates the vertex buffer by applying transformation from the bones.
  29945. * Returns the Mesh.
  29946. *
  29947. * @param {skeleton} skeleton to apply
  29948. */
  29949. Mesh.prototype.applySkeleton = function (skeleton) {
  29950. if (!this.geometry) {
  29951. return this;
  29952. }
  29953. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29954. return this;
  29955. }
  29956. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29957. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29958. return this;
  29959. }
  29960. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29961. return this;
  29962. }
  29963. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29964. return this;
  29965. }
  29966. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29967. return this;
  29968. }
  29969. if (!this._sourcePositions) {
  29970. var submeshes = this.subMeshes.slice();
  29971. this.setPositionsForCPUSkinning();
  29972. this.subMeshes = submeshes;
  29973. }
  29974. if (!this._sourceNormals) {
  29975. this.setNormalsForCPUSkinning();
  29976. }
  29977. // positionsData checks for not being Float32Array will only pass at most once
  29978. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29979. if (!positionsData) {
  29980. return this;
  29981. }
  29982. if (!(positionsData instanceof Float32Array)) {
  29983. positionsData = new Float32Array(positionsData);
  29984. }
  29985. // normalsData checks for not being Float32Array will only pass at most once
  29986. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29987. if (!normalsData) {
  29988. return this;
  29989. }
  29990. if (!(normalsData instanceof Float32Array)) {
  29991. normalsData = new Float32Array(normalsData);
  29992. }
  29993. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29994. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29995. if (!matricesWeightsData || !matricesIndicesData) {
  29996. return this;
  29997. }
  29998. var needExtras = this.numBoneInfluencers > 4;
  29999. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30000. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30001. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30002. var tempVector3 = BABYLON.Vector3.Zero();
  30003. var finalMatrix = new BABYLON.Matrix();
  30004. var tempMatrix = new BABYLON.Matrix();
  30005. var matWeightIdx = 0;
  30006. var inf;
  30007. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30008. var weight;
  30009. for (inf = 0; inf < 4; inf++) {
  30010. weight = matricesWeightsData[matWeightIdx + inf];
  30011. if (weight > 0) {
  30012. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30013. finalMatrix.addToSelf(tempMatrix);
  30014. }
  30015. else
  30016. break;
  30017. }
  30018. if (needExtras) {
  30019. for (inf = 0; inf < 4; inf++) {
  30020. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30021. if (weight > 0) {
  30022. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30023. finalMatrix.addToSelf(tempMatrix);
  30024. }
  30025. else
  30026. break;
  30027. }
  30028. }
  30029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30030. tempVector3.toArray(positionsData, index);
  30031. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30032. tempVector3.toArray(normalsData, index);
  30033. finalMatrix.reset();
  30034. }
  30035. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30036. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30037. return this;
  30038. };
  30039. // Tools
  30040. /**
  30041. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30042. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30043. */
  30044. Mesh.MinMax = function (meshes) {
  30045. var minVector = null;
  30046. var maxVector = null;
  30047. meshes.forEach(function (mesh, index, array) {
  30048. var boundingInfo = mesh.getBoundingInfo();
  30049. var boundingBox = boundingInfo.boundingBox;
  30050. if (!minVector || !maxVector) {
  30051. minVector = boundingBox.minimumWorld;
  30052. maxVector = boundingBox.maximumWorld;
  30053. }
  30054. else {
  30055. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30056. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30057. }
  30058. });
  30059. if (!minVector || !maxVector) {
  30060. return {
  30061. min: BABYLON.Vector3.Zero(),
  30062. max: BABYLON.Vector3.Zero()
  30063. };
  30064. }
  30065. return {
  30066. min: minVector,
  30067. max: maxVector
  30068. };
  30069. };
  30070. /**
  30071. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30072. */
  30073. Mesh.Center = function (meshesOrMinMaxVector) {
  30074. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30075. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30076. };
  30077. /**
  30078. * Merge the array of meshes into a single mesh for performance reasons.
  30079. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30080. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30081. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30082. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30083. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30084. */
  30085. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30086. if (disposeSource === void 0) { disposeSource = true; }
  30087. var index;
  30088. if (!allow32BitsIndices) {
  30089. var totalVertices = 0;
  30090. // Counting vertices
  30091. for (index = 0; index < meshes.length; index++) {
  30092. if (meshes[index]) {
  30093. totalVertices += meshes[index].getTotalVertices();
  30094. if (totalVertices > 65536) {
  30095. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30096. return null;
  30097. }
  30098. }
  30099. }
  30100. }
  30101. // Merge
  30102. var vertexData = null;
  30103. var otherVertexData;
  30104. var indiceArray = new Array();
  30105. var source = null;
  30106. for (index = 0; index < meshes.length; index++) {
  30107. if (meshes[index]) {
  30108. meshes[index].computeWorldMatrix(true);
  30109. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30110. otherVertexData.transform(meshes[index].getWorldMatrix());
  30111. if (vertexData) {
  30112. vertexData.merge(otherVertexData);
  30113. }
  30114. else {
  30115. vertexData = otherVertexData;
  30116. source = meshes[index];
  30117. }
  30118. if (subdivideWithSubMeshes) {
  30119. indiceArray.push(meshes[index].getTotalIndices());
  30120. }
  30121. }
  30122. }
  30123. source = source;
  30124. if (!meshSubclass) {
  30125. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30126. }
  30127. vertexData.applyToMesh(meshSubclass);
  30128. // Setting properties
  30129. meshSubclass.material = source.material;
  30130. meshSubclass.checkCollisions = source.checkCollisions;
  30131. // Cleaning
  30132. if (disposeSource) {
  30133. for (index = 0; index < meshes.length; index++) {
  30134. if (meshes[index]) {
  30135. meshes[index].dispose();
  30136. }
  30137. }
  30138. }
  30139. // Subdivide
  30140. if (subdivideWithSubMeshes) {
  30141. //-- Suppresions du submesh global
  30142. meshSubclass.releaseSubMeshes();
  30143. index = 0;
  30144. var offset = 0;
  30145. //-- aplique la subdivision en fonction du tableau d'indices
  30146. while (index < indiceArray.length) {
  30147. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30148. offset += indiceArray[index];
  30149. index++;
  30150. }
  30151. }
  30152. return meshSubclass;
  30153. };
  30154. // Consts
  30155. Mesh._FRONTSIDE = 0;
  30156. Mesh._BACKSIDE = 1;
  30157. Mesh._DOUBLESIDE = 2;
  30158. Mesh._DEFAULTSIDE = 0;
  30159. Mesh._NO_CAP = 0;
  30160. Mesh._CAP_START = 1;
  30161. Mesh._CAP_END = 2;
  30162. Mesh._CAP_ALL = 3;
  30163. return Mesh;
  30164. }(BABYLON.AbstractMesh));
  30165. BABYLON.Mesh = Mesh;
  30166. })(BABYLON || (BABYLON = {}));
  30167. //# sourceMappingURL=babylon.mesh.js.map
  30168. var BABYLON;
  30169. (function (BABYLON) {
  30170. var BaseSubMesh = /** @class */ (function () {
  30171. function BaseSubMesh() {
  30172. }
  30173. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30174. get: function () {
  30175. return this._materialEffect;
  30176. },
  30177. enumerable: true,
  30178. configurable: true
  30179. });
  30180. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30181. if (defines === void 0) { defines = null; }
  30182. if (this._materialEffect === effect) {
  30183. if (!effect) {
  30184. this._materialDefines = null;
  30185. }
  30186. return;
  30187. }
  30188. this._materialDefines = defines;
  30189. this._materialEffect = effect;
  30190. };
  30191. return BaseSubMesh;
  30192. }());
  30193. BABYLON.BaseSubMesh = BaseSubMesh;
  30194. var SubMesh = /** @class */ (function (_super) {
  30195. __extends(SubMesh, _super);
  30196. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30197. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30198. var _this = _super.call(this) || this;
  30199. _this.materialIndex = materialIndex;
  30200. _this.verticesStart = verticesStart;
  30201. _this.verticesCount = verticesCount;
  30202. _this.indexStart = indexStart;
  30203. _this.indexCount = indexCount;
  30204. _this._renderId = 0;
  30205. _this._mesh = mesh;
  30206. _this._renderingMesh = renderingMesh || mesh;
  30207. mesh.subMeshes.push(_this);
  30208. _this._trianglePlanes = [];
  30209. _this._id = mesh.subMeshes.length - 1;
  30210. if (createBoundingBox) {
  30211. _this.refreshBoundingInfo();
  30212. mesh.computeWorldMatrix(true);
  30213. }
  30214. return _this;
  30215. }
  30216. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30217. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30218. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30219. };
  30220. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30221. get: function () {
  30222. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30223. },
  30224. enumerable: true,
  30225. configurable: true
  30226. });
  30227. /**
  30228. * Returns the submesh BoudingInfo object.
  30229. */
  30230. SubMesh.prototype.getBoundingInfo = function () {
  30231. if (this.IsGlobal) {
  30232. return this._mesh.getBoundingInfo();
  30233. }
  30234. return this._boundingInfo;
  30235. };
  30236. /**
  30237. * Sets the submesh BoundingInfo.
  30238. * Return the SubMesh.
  30239. */
  30240. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30241. this._boundingInfo = boundingInfo;
  30242. return this;
  30243. };
  30244. /**
  30245. * Returns the mesh of the current submesh.
  30246. */
  30247. SubMesh.prototype.getMesh = function () {
  30248. return this._mesh;
  30249. };
  30250. /**
  30251. * Returns the rendering mesh of the submesh.
  30252. */
  30253. SubMesh.prototype.getRenderingMesh = function () {
  30254. return this._renderingMesh;
  30255. };
  30256. /**
  30257. * Returns the submesh material.
  30258. */
  30259. SubMesh.prototype.getMaterial = function () {
  30260. var rootMaterial = this._renderingMesh.material;
  30261. if (rootMaterial === null || rootMaterial === undefined) {
  30262. return this._mesh.getScene().defaultMaterial;
  30263. }
  30264. else if (rootMaterial.getSubMaterial) {
  30265. var multiMaterial = rootMaterial;
  30266. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30267. if (this._currentMaterial !== effectiveMaterial) {
  30268. this._currentMaterial = effectiveMaterial;
  30269. this._materialDefines = null;
  30270. }
  30271. return effectiveMaterial;
  30272. }
  30273. return rootMaterial;
  30274. };
  30275. // Methods
  30276. /**
  30277. * Sets a new updated BoundingInfo object to the submesh.
  30278. * Returns the SubMesh.
  30279. */
  30280. SubMesh.prototype.refreshBoundingInfo = function () {
  30281. this._lastColliderWorldVertices = null;
  30282. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30283. return this;
  30284. }
  30285. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30286. if (!data) {
  30287. this._boundingInfo = this._mesh.getBoundingInfo();
  30288. return this;
  30289. }
  30290. var indices = this._renderingMesh.getIndices();
  30291. var extend;
  30292. //is this the only submesh?
  30293. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30294. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30295. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30296. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30297. }
  30298. else {
  30299. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30300. }
  30301. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30302. return this;
  30303. };
  30304. SubMesh.prototype._checkCollision = function (collider) {
  30305. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30306. return boundingInfo._checkCollision(collider);
  30307. };
  30308. /**
  30309. * Updates the submesh BoundingInfo.
  30310. * Returns the Submesh.
  30311. */
  30312. SubMesh.prototype.updateBoundingInfo = function (world) {
  30313. var boundingInfo = this.getBoundingInfo();
  30314. if (!boundingInfo) {
  30315. this.refreshBoundingInfo();
  30316. boundingInfo = this.getBoundingInfo();
  30317. }
  30318. boundingInfo.update(world);
  30319. return this;
  30320. };
  30321. /**
  30322. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30323. * Boolean returned.
  30324. */
  30325. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30326. var boundingInfo = this.getBoundingInfo();
  30327. if (!boundingInfo) {
  30328. return false;
  30329. }
  30330. return boundingInfo.isInFrustum(frustumPlanes);
  30331. };
  30332. /**
  30333. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30334. * Boolean returned.
  30335. */
  30336. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30337. var boundingInfo = this.getBoundingInfo();
  30338. if (!boundingInfo) {
  30339. return false;
  30340. }
  30341. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30342. };
  30343. /**
  30344. * Renders the submesh.
  30345. * Returns it.
  30346. */
  30347. SubMesh.prototype.render = function (enableAlphaMode) {
  30348. this._renderingMesh.render(this, enableAlphaMode);
  30349. return this;
  30350. };
  30351. /**
  30352. * Returns a new Index Buffer.
  30353. * Type returned : WebGLBuffer.
  30354. */
  30355. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30356. if (!this._linesIndexBuffer) {
  30357. var linesIndices = [];
  30358. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30359. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30360. }
  30361. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30362. this.linesIndexCount = linesIndices.length;
  30363. }
  30364. return this._linesIndexBuffer;
  30365. };
  30366. /**
  30367. * True is the passed Ray intersects the submesh bounding box.
  30368. * Boolean returned.
  30369. */
  30370. SubMesh.prototype.canIntersects = function (ray) {
  30371. var boundingInfo = this.getBoundingInfo();
  30372. if (!boundingInfo) {
  30373. return false;
  30374. }
  30375. return ray.intersectsBox(boundingInfo.boundingBox);
  30376. };
  30377. /**
  30378. * Returns an object IntersectionInfo.
  30379. */
  30380. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30381. var intersectInfo = null;
  30382. // LineMesh first as it's also a Mesh...
  30383. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30384. var lineMesh = this._mesh;
  30385. // Line test
  30386. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30387. var p0 = positions[indices[index]];
  30388. var p1 = positions[indices[index + 1]];
  30389. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30390. if (length < 0) {
  30391. continue;
  30392. }
  30393. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30394. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30395. if (fastCheck) {
  30396. break;
  30397. }
  30398. }
  30399. }
  30400. }
  30401. else {
  30402. // Triangles test
  30403. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30404. var p0 = positions[indices[index]];
  30405. var p1 = positions[indices[index + 1]];
  30406. var p2 = positions[indices[index + 2]];
  30407. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30408. if (currentIntersectInfo) {
  30409. if (currentIntersectInfo.distance < 0) {
  30410. continue;
  30411. }
  30412. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30413. intersectInfo = currentIntersectInfo;
  30414. intersectInfo.faceId = index / 3;
  30415. if (fastCheck) {
  30416. break;
  30417. }
  30418. }
  30419. }
  30420. }
  30421. }
  30422. return intersectInfo;
  30423. };
  30424. SubMesh.prototype._rebuild = function () {
  30425. if (this._linesIndexBuffer) {
  30426. this._linesIndexBuffer = null;
  30427. }
  30428. };
  30429. // Clone
  30430. /**
  30431. * Creates a new Submesh from the passed Mesh.
  30432. */
  30433. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30434. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30435. if (!this.IsGlobal) {
  30436. var boundingInfo = this.getBoundingInfo();
  30437. if (!boundingInfo) {
  30438. return result;
  30439. }
  30440. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30441. }
  30442. return result;
  30443. };
  30444. // Dispose
  30445. /**
  30446. * Disposes the Submesh.
  30447. * Returns nothing.
  30448. */
  30449. SubMesh.prototype.dispose = function () {
  30450. if (this._linesIndexBuffer) {
  30451. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30452. this._linesIndexBuffer = null;
  30453. }
  30454. // Remove from mesh
  30455. var index = this._mesh.subMeshes.indexOf(this);
  30456. this._mesh.subMeshes.splice(index, 1);
  30457. };
  30458. // Statics
  30459. /**
  30460. * Creates a new Submesh from the passed parameters :
  30461. * - materialIndex (integer) : the index of the main mesh material.
  30462. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30463. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30464. * - mesh (Mesh) : the main mesh to create the submesh from.
  30465. * - renderingMesh (optional Mesh) : rendering mesh.
  30466. */
  30467. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30468. var minVertexIndex = Number.MAX_VALUE;
  30469. var maxVertexIndex = -Number.MAX_VALUE;
  30470. renderingMesh = (renderingMesh || mesh);
  30471. var indices = renderingMesh.getIndices();
  30472. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30473. var vertexIndex = indices[index];
  30474. if (vertexIndex < minVertexIndex)
  30475. minVertexIndex = vertexIndex;
  30476. if (vertexIndex > maxVertexIndex)
  30477. maxVertexIndex = vertexIndex;
  30478. }
  30479. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30480. };
  30481. return SubMesh;
  30482. }(BaseSubMesh));
  30483. BABYLON.SubMesh = SubMesh;
  30484. })(BABYLON || (BABYLON = {}));
  30485. //# sourceMappingURL=babylon.subMesh.js.map
  30486. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30487. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30488. s = arguments[i];
  30489. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30490. t[p] = s[p];
  30491. }
  30492. return t;
  30493. };
  30494. var BABYLON;
  30495. (function (BABYLON) {
  30496. /**
  30497. * Manages the defines for the Material.
  30498. */
  30499. var MaterialDefines = /** @class */ (function () {
  30500. function MaterialDefines() {
  30501. this._isDirty = true;
  30502. this._areLightsDirty = true;
  30503. this._areAttributesDirty = true;
  30504. this._areTexturesDirty = true;
  30505. this._areFresnelDirty = true;
  30506. this._areMiscDirty = true;
  30507. this._areImageProcessingDirty = true;
  30508. this._normals = false;
  30509. this._uvs = false;
  30510. this._needNormals = false;
  30511. this._needUVs = false;
  30512. }
  30513. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30514. /**
  30515. * Specifies if the material needs to be re-calculated.
  30516. */
  30517. get: function () {
  30518. return this._isDirty;
  30519. },
  30520. enumerable: true,
  30521. configurable: true
  30522. });
  30523. /**
  30524. * Marks the material to indicate that it has been re-calculated.
  30525. */
  30526. MaterialDefines.prototype.markAsProcessed = function () {
  30527. this._isDirty = false;
  30528. this._areAttributesDirty = false;
  30529. this._areTexturesDirty = false;
  30530. this._areFresnelDirty = false;
  30531. this._areLightsDirty = false;
  30532. this._areMiscDirty = false;
  30533. this._areImageProcessingDirty = false;
  30534. };
  30535. /**
  30536. * Marks the material to indicate that it needs to be re-calculated.
  30537. */
  30538. MaterialDefines.prototype.markAsUnprocessed = function () {
  30539. this._isDirty = true;
  30540. };
  30541. /**
  30542. * Marks the material to indicate all of its defines need to be re-calculated.
  30543. */
  30544. MaterialDefines.prototype.markAllAsDirty = function () {
  30545. this._areTexturesDirty = true;
  30546. this._areAttributesDirty = true;
  30547. this._areLightsDirty = true;
  30548. this._areFresnelDirty = true;
  30549. this._areMiscDirty = true;
  30550. this._areImageProcessingDirty = true;
  30551. this._isDirty = true;
  30552. };
  30553. /**
  30554. * Marks the material to indicate that image processing needs to be re-calculated.
  30555. */
  30556. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30557. this._areImageProcessingDirty = true;
  30558. this._isDirty = true;
  30559. };
  30560. /**
  30561. * Marks the material to indicate the lights need to be re-calculated.
  30562. */
  30563. MaterialDefines.prototype.markAsLightDirty = function () {
  30564. this._areLightsDirty = true;
  30565. this._isDirty = true;
  30566. };
  30567. /**
  30568. * Marks the attribute state as changed.
  30569. */
  30570. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30571. this._areAttributesDirty = true;
  30572. this._isDirty = true;
  30573. };
  30574. /**
  30575. * Marks the texture state as changed.
  30576. */
  30577. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30578. this._areTexturesDirty = true;
  30579. this._isDirty = true;
  30580. };
  30581. /**
  30582. * Marks the fresnel state as changed.
  30583. */
  30584. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30585. this._areFresnelDirty = true;
  30586. this._isDirty = true;
  30587. };
  30588. /**
  30589. * Marks the misc state as changed.
  30590. */
  30591. MaterialDefines.prototype.markAsMiscDirty = function () {
  30592. this._areMiscDirty = true;
  30593. this._isDirty = true;
  30594. };
  30595. /**
  30596. * Rebuilds the material defines.
  30597. */
  30598. MaterialDefines.prototype.rebuild = function () {
  30599. if (this._keys) {
  30600. delete this._keys;
  30601. }
  30602. this._keys = [];
  30603. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30604. var key = _a[_i];
  30605. if (key[0] === "_") {
  30606. continue;
  30607. }
  30608. this._keys.push(key);
  30609. }
  30610. };
  30611. /**
  30612. * Specifies if two material defines are equal.
  30613. * @param other - A material define instance to compare to.
  30614. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30615. */
  30616. MaterialDefines.prototype.isEqual = function (other) {
  30617. if (this._keys.length !== other._keys.length) {
  30618. return false;
  30619. }
  30620. for (var index = 0; index < this._keys.length; index++) {
  30621. var prop = this._keys[index];
  30622. if (this[prop] !== other[prop]) {
  30623. return false;
  30624. }
  30625. }
  30626. return true;
  30627. };
  30628. /**
  30629. * Clones this instance's defines to another instance.
  30630. * @param other - material defines to clone values to.
  30631. */
  30632. MaterialDefines.prototype.cloneTo = function (other) {
  30633. if (this._keys.length !== other._keys.length) {
  30634. other._keys = this._keys.slice(0);
  30635. }
  30636. for (var index = 0; index < this._keys.length; index++) {
  30637. var prop = this._keys[index];
  30638. other[prop] = this[prop];
  30639. }
  30640. };
  30641. /**
  30642. * Resets the material define values.
  30643. */
  30644. MaterialDefines.prototype.reset = function () {
  30645. for (var index = 0; index < this._keys.length; index++) {
  30646. var prop = this._keys[index];
  30647. if (typeof (this[prop]) === "number") {
  30648. this[prop] = 0;
  30649. }
  30650. else {
  30651. this[prop] = false;
  30652. }
  30653. }
  30654. };
  30655. /**
  30656. * Converts the material define values to a string.
  30657. * @returns - String of material define information.
  30658. */
  30659. MaterialDefines.prototype.toString = function () {
  30660. var result = "";
  30661. for (var index = 0; index < this._keys.length; index++) {
  30662. var prop = this._keys[index];
  30663. var value = this[prop];
  30664. if (typeof (value) === "number") {
  30665. result += "#define " + prop + " " + this[prop] + "\n";
  30666. }
  30667. else if (value) {
  30668. result += "#define " + prop + "\n";
  30669. }
  30670. }
  30671. return result;
  30672. };
  30673. return MaterialDefines;
  30674. }());
  30675. BABYLON.MaterialDefines = MaterialDefines;
  30676. /**
  30677. * This offers the main features of a material in BJS.
  30678. */
  30679. var Material = /** @class */ (function () {
  30680. /**
  30681. * Creates a material instance.
  30682. * @param name - The name of the material.
  30683. * @param scene - The BJS scene to reference.
  30684. * @param doNotAdd - Specifies if the material should be added to the scene.
  30685. */
  30686. function Material(name, scene, doNotAdd) {
  30687. /**
  30688. * Specifies if the ready state should be checked on each call.
  30689. */
  30690. this.checkReadyOnEveryCall = false;
  30691. /**
  30692. * Specifies if the ready state should be checked once.
  30693. */
  30694. this.checkReadyOnlyOnce = false;
  30695. /**
  30696. * The state of the material.
  30697. */
  30698. this.state = "";
  30699. /**
  30700. * The alpha value of the material.
  30701. */
  30702. this._alpha = 1.0;
  30703. /**
  30704. * Specifies if back face culling is enabled.
  30705. */
  30706. this._backFaceCulling = true;
  30707. /**
  30708. * Specifies if the material should be serialized.
  30709. */
  30710. this.doNotSerialize = false;
  30711. /**
  30712. * Specifies if the effect should be stored on sub meshes.
  30713. */
  30714. this.storeEffectOnSubMeshes = false;
  30715. /**
  30716. * An event triggered when the material is disposed.
  30717. * @type {BABYLON.Observable}
  30718. */
  30719. this.onDisposeObservable = new BABYLON.Observable();
  30720. /**
  30721. * An event triggered when the material is bound.
  30722. * @type {BABYLON.Observable}
  30723. */
  30724. this.onBindObservable = new BABYLON.Observable();
  30725. /**
  30726. * An event triggered when the material is unbound.
  30727. * @type {BABYLON.Observable}
  30728. */
  30729. this.onUnBindObservable = new BABYLON.Observable();
  30730. /**
  30731. * Stores the value of the alpha mode.
  30732. */
  30733. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30734. /**
  30735. * Stores the state of the need depth pre-pass value.
  30736. */
  30737. this._needDepthPrePass = false;
  30738. /**
  30739. * Specifies if depth writing should be disabled.
  30740. */
  30741. this.disableDepthWrite = false;
  30742. /**
  30743. * Specifies if depth writing should be forced.
  30744. */
  30745. this.forceDepthWrite = false;
  30746. /**
  30747. * Specifies if there should be a separate pass for culling.
  30748. */
  30749. this.separateCullingPass = false;
  30750. /**
  30751. * Stores the state specifing if fog should be enabled.
  30752. */
  30753. this._fogEnabled = true;
  30754. /**
  30755. * Stores the size of points.
  30756. */
  30757. this.pointSize = 1.0;
  30758. /**
  30759. * Stores the z offset value.
  30760. */
  30761. this.zOffset = 0;
  30762. /**
  30763. * Specifies if the material was previously ready.
  30764. */
  30765. this._wasPreviouslyReady = false;
  30766. /**
  30767. * Stores the fill mode state.
  30768. */
  30769. this._fillMode = Material.TriangleFillMode;
  30770. this.name = name;
  30771. this.id = name || BABYLON.Tools.RandomId();
  30772. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30773. if (this._scene.useRightHandedSystem) {
  30774. this.sideOrientation = Material.ClockWiseSideOrientation;
  30775. }
  30776. else {
  30777. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30778. }
  30779. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30780. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30781. if (!doNotAdd) {
  30782. this._scene.materials.push(this);
  30783. }
  30784. }
  30785. Object.defineProperty(Material, "TriangleFillMode", {
  30786. /**
  30787. * Returns the triangle fill mode.
  30788. */
  30789. get: function () {
  30790. return Material._TriangleFillMode;
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. Object.defineProperty(Material, "WireFrameFillMode", {
  30796. /**
  30797. * Returns the wireframe mode.
  30798. */
  30799. get: function () {
  30800. return Material._WireFrameFillMode;
  30801. },
  30802. enumerable: true,
  30803. configurable: true
  30804. });
  30805. Object.defineProperty(Material, "PointFillMode", {
  30806. /**
  30807. * Returns the point fill mode.
  30808. */
  30809. get: function () {
  30810. return Material._PointFillMode;
  30811. },
  30812. enumerable: true,
  30813. configurable: true
  30814. });
  30815. Object.defineProperty(Material, "PointListDrawMode", {
  30816. /**
  30817. * Returns the point list draw mode.
  30818. */
  30819. get: function () {
  30820. return Material._PointListDrawMode;
  30821. },
  30822. enumerable: true,
  30823. configurable: true
  30824. });
  30825. Object.defineProperty(Material, "LineListDrawMode", {
  30826. /**
  30827. * Returns the line list draw mode.
  30828. */
  30829. get: function () {
  30830. return Material._LineListDrawMode;
  30831. },
  30832. enumerable: true,
  30833. configurable: true
  30834. });
  30835. Object.defineProperty(Material, "LineLoopDrawMode", {
  30836. /**
  30837. * Returns the line loop draw mode.
  30838. */
  30839. get: function () {
  30840. return Material._LineLoopDrawMode;
  30841. },
  30842. enumerable: true,
  30843. configurable: true
  30844. });
  30845. Object.defineProperty(Material, "LineStripDrawMode", {
  30846. /**
  30847. * Returns the line strip draw mode.
  30848. */
  30849. get: function () {
  30850. return Material._LineStripDrawMode;
  30851. },
  30852. enumerable: true,
  30853. configurable: true
  30854. });
  30855. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30856. /**
  30857. * Returns the triangle strip draw mode.
  30858. */
  30859. get: function () {
  30860. return Material._TriangleStripDrawMode;
  30861. },
  30862. enumerable: true,
  30863. configurable: true
  30864. });
  30865. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30866. /**
  30867. * Returns the triangle fan draw mode.
  30868. */
  30869. get: function () {
  30870. return Material._TriangleFanDrawMode;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30876. /**
  30877. * Returns the clock-wise side orientation.
  30878. */
  30879. get: function () {
  30880. return Material._ClockWiseSideOrientation;
  30881. },
  30882. enumerable: true,
  30883. configurable: true
  30884. });
  30885. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30886. /**
  30887. * Returns the counter clock-wise side orientation.
  30888. */
  30889. get: function () {
  30890. return Material._CounterClockWiseSideOrientation;
  30891. },
  30892. enumerable: true,
  30893. configurable: true
  30894. });
  30895. Object.defineProperty(Material, "TextureDirtyFlag", {
  30896. /**
  30897. * Returns the dirty texture flag value.
  30898. */
  30899. get: function () {
  30900. return Material._TextureDirtyFlag;
  30901. },
  30902. enumerable: true,
  30903. configurable: true
  30904. });
  30905. Object.defineProperty(Material, "LightDirtyFlag", {
  30906. /**
  30907. * Returns the dirty light flag value.
  30908. */
  30909. get: function () {
  30910. return Material._LightDirtyFlag;
  30911. },
  30912. enumerable: true,
  30913. configurable: true
  30914. });
  30915. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30916. /**
  30917. * Returns the dirty fresnel flag value.
  30918. */
  30919. get: function () {
  30920. return Material._FresnelDirtyFlag;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30926. /**
  30927. * Returns the dirty attributes flag value.
  30928. */
  30929. get: function () {
  30930. return Material._AttributesDirtyFlag;
  30931. },
  30932. enumerable: true,
  30933. configurable: true
  30934. });
  30935. Object.defineProperty(Material, "MiscDirtyFlag", {
  30936. /**
  30937. * Returns the dirty misc flag value.
  30938. */
  30939. get: function () {
  30940. return Material._MiscDirtyFlag;
  30941. },
  30942. enumerable: true,
  30943. configurable: true
  30944. });
  30945. Object.defineProperty(Material.prototype, "alpha", {
  30946. /**
  30947. * Gets the alpha value of the material.
  30948. */
  30949. get: function () {
  30950. return this._alpha;
  30951. },
  30952. /**
  30953. * Sets the alpha value of the material.
  30954. */
  30955. set: function (value) {
  30956. if (this._alpha === value) {
  30957. return;
  30958. }
  30959. this._alpha = value;
  30960. this.markAsDirty(Material.MiscDirtyFlag);
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30966. /**
  30967. * Gets the back-face culling state.
  30968. */
  30969. get: function () {
  30970. return this._backFaceCulling;
  30971. },
  30972. /**
  30973. * Sets the back-face culling state.
  30974. */
  30975. set: function (value) {
  30976. if (this._backFaceCulling === value) {
  30977. return;
  30978. }
  30979. this._backFaceCulling = value;
  30980. this.markAsDirty(Material.TextureDirtyFlag);
  30981. },
  30982. enumerable: true,
  30983. configurable: true
  30984. });
  30985. Object.defineProperty(Material.prototype, "onDispose", {
  30986. /**
  30987. * Called during a dispose event.
  30988. */
  30989. set: function (callback) {
  30990. if (this._onDisposeObserver) {
  30991. this.onDisposeObservable.remove(this._onDisposeObserver);
  30992. }
  30993. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. Object.defineProperty(Material.prototype, "onBind", {
  30999. /**
  31000. * Called during a bind event.
  31001. */
  31002. set: function (callback) {
  31003. if (this._onBindObserver) {
  31004. this.onBindObservable.remove(this._onBindObserver);
  31005. }
  31006. this._onBindObserver = this.onBindObservable.add(callback);
  31007. },
  31008. enumerable: true,
  31009. configurable: true
  31010. });
  31011. Object.defineProperty(Material.prototype, "alphaMode", {
  31012. /**
  31013. * Gets the value of the alpha mode.
  31014. */
  31015. get: function () {
  31016. return this._alphaMode;
  31017. },
  31018. /**
  31019. * Sets the value of the alpha mode.
  31020. */
  31021. set: function (value) {
  31022. if (this._alphaMode === value) {
  31023. return;
  31024. }
  31025. this._alphaMode = value;
  31026. this.markAsDirty(Material.TextureDirtyFlag);
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31032. /**
  31033. * Gets the depth pre-pass value.
  31034. */
  31035. get: function () {
  31036. return this._needDepthPrePass;
  31037. },
  31038. /**
  31039. * Sets the need depth pre-pass value.
  31040. */
  31041. set: function (value) {
  31042. if (this._needDepthPrePass === value) {
  31043. return;
  31044. }
  31045. this._needDepthPrePass = value;
  31046. if (this._needDepthPrePass) {
  31047. this.checkReadyOnEveryCall = true;
  31048. }
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Object.defineProperty(Material.prototype, "fogEnabled", {
  31054. /**
  31055. * Gets the value of the fog enabled state.
  31056. */
  31057. get: function () {
  31058. return this._fogEnabled;
  31059. },
  31060. /**
  31061. * Sets the state for enabling fog.
  31062. */
  31063. set: function (value) {
  31064. if (this._fogEnabled === value) {
  31065. return;
  31066. }
  31067. this._fogEnabled = value;
  31068. this.markAsDirty(Material.MiscDirtyFlag);
  31069. },
  31070. enumerable: true,
  31071. configurable: true
  31072. });
  31073. Object.defineProperty(Material.prototype, "wireframe", {
  31074. /**
  31075. * Gets a value specifying if wireframe mode is enabled.
  31076. */
  31077. get: function () {
  31078. return this._fillMode === Material.WireFrameFillMode;
  31079. },
  31080. /**
  31081. * Sets the state of wireframe mode.
  31082. */
  31083. set: function (value) {
  31084. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. Object.defineProperty(Material.prototype, "pointsCloud", {
  31090. /**
  31091. * Gets the value specifying if point clouds are enabled.
  31092. */
  31093. get: function () {
  31094. return this._fillMode === Material.PointFillMode;
  31095. },
  31096. /**
  31097. * Sets the state of point cloud mode.
  31098. */
  31099. set: function (value) {
  31100. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. Object.defineProperty(Material.prototype, "fillMode", {
  31106. /**
  31107. * Gets the material fill mode.
  31108. */
  31109. get: function () {
  31110. return this._fillMode;
  31111. },
  31112. /**
  31113. * Sets the material fill mode.
  31114. */
  31115. set: function (value) {
  31116. if (this._fillMode === value) {
  31117. return;
  31118. }
  31119. this._fillMode = value;
  31120. this.markAsDirty(Material.MiscDirtyFlag);
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. /**
  31126. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31127. * subclasses should override adding information pertainent to themselves.
  31128. * @returns - String with material information.
  31129. */
  31130. Material.prototype.toString = function (fullDetails) {
  31131. var ret = "Name: " + this.name;
  31132. if (fullDetails) {
  31133. }
  31134. return ret;
  31135. };
  31136. /**
  31137. * Gets the class name of the material.
  31138. * @returns - String with the class name of the material.
  31139. */
  31140. Material.prototype.getClassName = function () {
  31141. return "Material";
  31142. };
  31143. Object.defineProperty(Material.prototype, "isFrozen", {
  31144. /**
  31145. * Specifies if updates for the material been locked.
  31146. */
  31147. get: function () {
  31148. return this.checkReadyOnlyOnce;
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. /**
  31154. * Locks updates for the material.
  31155. */
  31156. Material.prototype.freeze = function () {
  31157. this.checkReadyOnlyOnce = true;
  31158. };
  31159. /**
  31160. * Unlocks updates for the material.
  31161. */
  31162. Material.prototype.unfreeze = function () {
  31163. this.checkReadyOnlyOnce = false;
  31164. };
  31165. /**
  31166. * Specifies if the material is ready to be used.
  31167. * @param mesh - BJS mesh.
  31168. * @param useInstances - Specifies if instances should be used.
  31169. * @returns - Boolean indicating if the material is ready to be used.
  31170. */
  31171. Material.prototype.isReady = function (mesh, useInstances) {
  31172. return true;
  31173. };
  31174. /**
  31175. * Specifies that the submesh is ready to be used.
  31176. * @param mesh - BJS mesh.
  31177. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31178. * @param useInstances - Specifies that instances should be used.
  31179. * @returns - boolean indicating that the submesh is ready or not.
  31180. */
  31181. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31182. return false;
  31183. };
  31184. /**
  31185. * Returns the material effect.
  31186. * @returns - Nullable material effect.
  31187. */
  31188. Material.prototype.getEffect = function () {
  31189. return this._effect;
  31190. };
  31191. /**
  31192. * Returns the BJS scene.
  31193. * @returns - BJS Scene.
  31194. */
  31195. Material.prototype.getScene = function () {
  31196. return this._scene;
  31197. };
  31198. /**
  31199. * Specifies if the material will require alpha blending
  31200. * @returns - Boolean specifying if alpha blending is needed.
  31201. */
  31202. Material.prototype.needAlphaBlending = function () {
  31203. return (this.alpha < 1.0);
  31204. };
  31205. /**
  31206. * Specifies if the mesh will require alpha blending.
  31207. * @param mesh - BJS mesh.
  31208. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31209. */
  31210. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31211. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31212. };
  31213. /**
  31214. * Specifies if this material should be rendered in alpha test mode.
  31215. * @returns - Boolean specifying if an alpha test is needed.
  31216. */
  31217. Material.prototype.needAlphaTesting = function () {
  31218. return false;
  31219. };
  31220. /**
  31221. * Gets the texture used for the alpha test.
  31222. * @returns - Nullable alpha test texture.
  31223. */
  31224. Material.prototype.getAlphaTestTexture = function () {
  31225. return null;
  31226. };
  31227. /**
  31228. * Marks the material to indicate that it needs to be re-calculated.
  31229. */
  31230. Material.prototype.markDirty = function () {
  31231. this._wasPreviouslyReady = false;
  31232. };
  31233. Material.prototype._preBind = function (effect, overrideOrientation) {
  31234. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31235. var engine = this._scene.getEngine();
  31236. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31237. var reverse = orientation === Material.ClockWiseSideOrientation;
  31238. engine.enableEffect(effect ? effect : this._effect);
  31239. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31240. return reverse;
  31241. };
  31242. /**
  31243. * Binds the material to the mesh.
  31244. * @param world - World transformation matrix.
  31245. * @param mesh - Mesh to bind the material to.
  31246. */
  31247. Material.prototype.bind = function (world, mesh) {
  31248. };
  31249. /**
  31250. * Binds the submesh to the material.
  31251. * @param world - World transformation matrix.
  31252. * @param mesh - Mesh containing the submesh.
  31253. * @param subMesh - Submesh to bind the material to.
  31254. */
  31255. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31256. };
  31257. /**
  31258. * Binds the world matrix to the material.
  31259. * @param world - World transformation matrix.
  31260. */
  31261. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31262. };
  31263. /**
  31264. * Binds the scene's uniform buffer to the effect.
  31265. * @param effect - Effect to bind to the scene uniform buffer.
  31266. * @param sceneUbo - Scene uniform buffer.
  31267. */
  31268. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31269. sceneUbo.bindToEffect(effect, "Scene");
  31270. };
  31271. /**
  31272. * Binds the view matrix to the effect.
  31273. * @param effect - Effect to bind the view matrix to.
  31274. */
  31275. Material.prototype.bindView = function (effect) {
  31276. if (!this._useUBO) {
  31277. effect.setMatrix("view", this.getScene().getViewMatrix());
  31278. }
  31279. else {
  31280. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31281. }
  31282. };
  31283. /**
  31284. * Binds the view projection matrix to the effect.
  31285. * @param effect - Effect to bind the view projection matrix to.
  31286. */
  31287. Material.prototype.bindViewProjection = function (effect) {
  31288. if (!this._useUBO) {
  31289. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31290. }
  31291. else {
  31292. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31293. }
  31294. };
  31295. /**
  31296. * Specifies if material alpha testing should be turned on for the mesh.
  31297. * @param mesh - BJS mesh.
  31298. */
  31299. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31300. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31301. };
  31302. /**
  31303. * Processes to execute after binding the material to a mesh.
  31304. * @param mesh - BJS mesh.
  31305. */
  31306. Material.prototype._afterBind = function (mesh) {
  31307. this._scene._cachedMaterial = this;
  31308. if (mesh) {
  31309. this._scene._cachedVisibility = mesh.visibility;
  31310. }
  31311. else {
  31312. this._scene._cachedVisibility = 1;
  31313. }
  31314. if (mesh) {
  31315. this.onBindObservable.notifyObservers(mesh);
  31316. }
  31317. if (this.disableDepthWrite) {
  31318. var engine = this._scene.getEngine();
  31319. this._cachedDepthWriteState = engine.getDepthWrite();
  31320. engine.setDepthWrite(false);
  31321. }
  31322. };
  31323. /**
  31324. * Unbinds the material from the mesh.
  31325. */
  31326. Material.prototype.unbind = function () {
  31327. this.onUnBindObservable.notifyObservers(this);
  31328. if (this.disableDepthWrite) {
  31329. var engine = this._scene.getEngine();
  31330. engine.setDepthWrite(this._cachedDepthWriteState);
  31331. }
  31332. };
  31333. /**
  31334. * Gets the active textures from the material.
  31335. * @returns - Array of textures.
  31336. */
  31337. Material.prototype.getActiveTextures = function () {
  31338. return [];
  31339. };
  31340. /**
  31341. * Specifies if the material uses a texture.
  31342. * @param texture - Texture to check against the material.
  31343. * @returns - Boolean specifying if the material uses the texture.
  31344. */
  31345. Material.prototype.hasTexture = function (texture) {
  31346. return false;
  31347. };
  31348. /**
  31349. * Makes a duplicate of the material, and gives it a new name.
  31350. * @param name - Name to call the duplicated material.
  31351. * @returns - Nullable cloned material
  31352. */
  31353. Material.prototype.clone = function (name) {
  31354. return null;
  31355. };
  31356. /**
  31357. * Gets the meshes bound to the material.
  31358. * @returns - Array of meshes bound to the material.
  31359. */
  31360. Material.prototype.getBindedMeshes = function () {
  31361. var result = new Array();
  31362. for (var index = 0; index < this._scene.meshes.length; index++) {
  31363. var mesh = this._scene.meshes[index];
  31364. if (mesh.material === this) {
  31365. result.push(mesh);
  31366. }
  31367. }
  31368. return result;
  31369. };
  31370. /**
  31371. * Force shader compilation
  31372. * @param mesh - BJS mesh.
  31373. * @param onCompiled - function to execute once the material is compiled.
  31374. * @param options - options to pass to this function.
  31375. */
  31376. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31377. var _this = this;
  31378. var localOptions = __assign({ clipPlane: false }, options);
  31379. var subMesh = new BABYLON.BaseSubMesh();
  31380. var scene = this.getScene();
  31381. var checkReady = function () {
  31382. if (!_this._scene || !_this._scene.getEngine()) {
  31383. return;
  31384. }
  31385. if (subMesh._materialDefines) {
  31386. subMesh._materialDefines._renderId = -1;
  31387. }
  31388. var clipPlaneState = scene.clipPlane;
  31389. if (localOptions.clipPlane) {
  31390. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31391. }
  31392. if (_this.storeEffectOnSubMeshes) {
  31393. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31394. if (onCompiled) {
  31395. onCompiled(_this);
  31396. }
  31397. }
  31398. else {
  31399. setTimeout(checkReady, 16);
  31400. }
  31401. }
  31402. else {
  31403. if (_this.isReady(mesh)) {
  31404. if (onCompiled) {
  31405. onCompiled(_this);
  31406. }
  31407. }
  31408. else {
  31409. setTimeout(checkReady, 16);
  31410. }
  31411. }
  31412. if (localOptions.clipPlane) {
  31413. scene.clipPlane = clipPlaneState;
  31414. }
  31415. };
  31416. checkReady();
  31417. };
  31418. /**
  31419. * Force shader compilation.
  31420. * @param mesh The mesh that will use this material
  31421. * @param options Additional options for compiling the shaders
  31422. * @returns A promise that resolves when the compilation completes
  31423. */
  31424. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31425. var _this = this;
  31426. return new Promise(function (resolve) {
  31427. _this.forceCompilation(mesh, function () {
  31428. resolve();
  31429. }, options);
  31430. });
  31431. };
  31432. /**
  31433. * Marks a define in the material to indicate that it needs to be re-computed.
  31434. * @param flag - Material define flag.
  31435. */
  31436. Material.prototype.markAsDirty = function (flag) {
  31437. if (flag & Material.TextureDirtyFlag) {
  31438. this._markAllSubMeshesAsTexturesDirty();
  31439. }
  31440. if (flag & Material.LightDirtyFlag) {
  31441. this._markAllSubMeshesAsLightsDirty();
  31442. }
  31443. if (flag & Material.FresnelDirtyFlag) {
  31444. this._markAllSubMeshesAsFresnelDirty();
  31445. }
  31446. if (flag & Material.AttributesDirtyFlag) {
  31447. this._markAllSubMeshesAsAttributesDirty();
  31448. }
  31449. if (flag & Material.MiscDirtyFlag) {
  31450. this._markAllSubMeshesAsMiscDirty();
  31451. }
  31452. this.getScene().resetCachedMaterial();
  31453. };
  31454. /**
  31455. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31456. * @param func - function which checks material defines against the submeshes.
  31457. */
  31458. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31459. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31460. var mesh = _a[_i];
  31461. if (!mesh.subMeshes) {
  31462. continue;
  31463. }
  31464. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31465. var subMesh = _c[_b];
  31466. if (subMesh.getMaterial() !== this) {
  31467. continue;
  31468. }
  31469. if (!subMesh._materialDefines) {
  31470. continue;
  31471. }
  31472. func(subMesh._materialDefines);
  31473. }
  31474. }
  31475. };
  31476. /**
  31477. * Indicates that image processing needs to be re-calculated for all submeshes.
  31478. */
  31479. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31480. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31481. };
  31482. /**
  31483. * Indicates that textures need to be re-calculated for all submeshes.
  31484. */
  31485. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31486. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31487. };
  31488. /**
  31489. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31490. */
  31491. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31492. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31493. };
  31494. /**
  31495. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31496. */
  31497. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31498. this._markAllSubMeshesAsDirty(function (defines) {
  31499. defines.markAsFresnelDirty();
  31500. defines.markAsMiscDirty();
  31501. });
  31502. };
  31503. /**
  31504. * Indicates that lights need to be re-calculated for all submeshes.
  31505. */
  31506. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31507. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31508. };
  31509. /**
  31510. * Indicates that attributes need to be re-calculated for all submeshes.
  31511. */
  31512. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31513. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31514. };
  31515. /**
  31516. * Indicates that misc needs to be re-calculated for all submeshes.
  31517. */
  31518. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31519. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31520. };
  31521. /**
  31522. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31523. */
  31524. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31525. this._markAllSubMeshesAsDirty(function (defines) {
  31526. defines.markAsTexturesDirty();
  31527. defines.markAsMiscDirty();
  31528. });
  31529. };
  31530. /**
  31531. * Disposes the material.
  31532. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31533. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31534. */
  31535. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31536. // Animations
  31537. this.getScene().stopAnimation(this);
  31538. // Remove from scene
  31539. var index = this._scene.materials.indexOf(this);
  31540. if (index >= 0) {
  31541. this._scene.materials.splice(index, 1);
  31542. }
  31543. // Remove from meshes
  31544. for (index = 0; index < this._scene.meshes.length; index++) {
  31545. var mesh = this._scene.meshes[index];
  31546. if (mesh.material === this) {
  31547. mesh.material = null;
  31548. if (mesh.geometry) {
  31549. var geometry = (mesh.geometry);
  31550. if (this.storeEffectOnSubMeshes) {
  31551. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31552. var subMesh = _a[_i];
  31553. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31554. if (forceDisposeEffect && subMesh._materialEffect) {
  31555. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31556. }
  31557. }
  31558. }
  31559. else {
  31560. geometry._releaseVertexArrayObject(this._effect);
  31561. }
  31562. }
  31563. }
  31564. }
  31565. this._uniformBuffer.dispose();
  31566. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31567. if (forceDisposeEffect && this._effect) {
  31568. if (!this.storeEffectOnSubMeshes) {
  31569. this._scene.getEngine()._releaseEffect(this._effect);
  31570. }
  31571. this._effect = null;
  31572. }
  31573. // Callback
  31574. this.onDisposeObservable.notifyObservers(this);
  31575. this.onDisposeObservable.clear();
  31576. this.onBindObservable.clear();
  31577. this.onUnBindObservable.clear();
  31578. };
  31579. /**
  31580. * Serializes this material.
  31581. * @returns - serialized material object.
  31582. */
  31583. Material.prototype.serialize = function () {
  31584. return BABYLON.SerializationHelper.Serialize(this);
  31585. };
  31586. /**
  31587. * Creates a MultiMaterial from parse MultiMaterial data.
  31588. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31589. * @param scene - BJS scene.
  31590. * @returns - MultiMaterial.
  31591. */
  31592. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31593. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31594. multiMaterial.id = parsedMultiMaterial.id;
  31595. if (BABYLON.Tags) {
  31596. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31597. }
  31598. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31599. var subMatId = parsedMultiMaterial.materials[matIndex];
  31600. if (subMatId) {
  31601. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31602. }
  31603. else {
  31604. multiMaterial.subMaterials.push(null);
  31605. }
  31606. }
  31607. return multiMaterial;
  31608. };
  31609. /**
  31610. * Creates a material from parsed material data.
  31611. * @param parsedMaterial - Parsed material data.
  31612. * @param scene - BJS scene.
  31613. * @param rootUrl - Root URL containing the material information.
  31614. * @returns - Parsed material.
  31615. */
  31616. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31617. if (!parsedMaterial.customType) {
  31618. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31619. }
  31620. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31621. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31622. if (!BABYLON.LegacyPBRMaterial) {
  31623. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31624. return;
  31625. }
  31626. }
  31627. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31628. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31629. ;
  31630. };
  31631. // Triangle views
  31632. Material._TriangleFillMode = 0;
  31633. Material._WireFrameFillMode = 1;
  31634. Material._PointFillMode = 2;
  31635. // Draw modes
  31636. Material._PointListDrawMode = 3;
  31637. Material._LineListDrawMode = 4;
  31638. Material._LineLoopDrawMode = 5;
  31639. Material._LineStripDrawMode = 6;
  31640. Material._TriangleStripDrawMode = 7;
  31641. Material._TriangleFanDrawMode = 8;
  31642. /**
  31643. * Stores the clock-wise side orientation.
  31644. */
  31645. Material._ClockWiseSideOrientation = 0;
  31646. /**
  31647. * Stores the counter clock-wise side orientation.
  31648. */
  31649. Material._CounterClockWiseSideOrientation = 1;
  31650. /**
  31651. * The dirty texture flag value.
  31652. */
  31653. Material._TextureDirtyFlag = 1;
  31654. /**
  31655. * The dirty light flag value.
  31656. */
  31657. Material._LightDirtyFlag = 2;
  31658. /**
  31659. * The dirty fresnel flag value.
  31660. */
  31661. Material._FresnelDirtyFlag = 4;
  31662. /**
  31663. * The dirty attribute flag value.
  31664. */
  31665. Material._AttributesDirtyFlag = 8;
  31666. /**
  31667. * The dirty misc flag value.
  31668. */
  31669. Material._MiscDirtyFlag = 16;
  31670. __decorate([
  31671. BABYLON.serialize()
  31672. ], Material.prototype, "id", void 0);
  31673. __decorate([
  31674. BABYLON.serialize()
  31675. ], Material.prototype, "name", void 0);
  31676. __decorate([
  31677. BABYLON.serialize()
  31678. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31679. __decorate([
  31680. BABYLON.serialize()
  31681. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31682. __decorate([
  31683. BABYLON.serialize()
  31684. ], Material.prototype, "state", void 0);
  31685. __decorate([
  31686. BABYLON.serialize("alpha")
  31687. ], Material.prototype, "_alpha", void 0);
  31688. __decorate([
  31689. BABYLON.serialize("backFaceCulling")
  31690. ], Material.prototype, "_backFaceCulling", void 0);
  31691. __decorate([
  31692. BABYLON.serialize()
  31693. ], Material.prototype, "sideOrientation", void 0);
  31694. __decorate([
  31695. BABYLON.serialize("alphaMode")
  31696. ], Material.prototype, "_alphaMode", void 0);
  31697. __decorate([
  31698. BABYLON.serialize()
  31699. ], Material.prototype, "_needDepthPrePass", void 0);
  31700. __decorate([
  31701. BABYLON.serialize()
  31702. ], Material.prototype, "disableDepthWrite", void 0);
  31703. __decorate([
  31704. BABYLON.serialize()
  31705. ], Material.prototype, "forceDepthWrite", void 0);
  31706. __decorate([
  31707. BABYLON.serialize()
  31708. ], Material.prototype, "separateCullingPass", void 0);
  31709. __decorate([
  31710. BABYLON.serialize("fogEnabled")
  31711. ], Material.prototype, "_fogEnabled", void 0);
  31712. __decorate([
  31713. BABYLON.serialize()
  31714. ], Material.prototype, "pointSize", void 0);
  31715. __decorate([
  31716. BABYLON.serialize()
  31717. ], Material.prototype, "zOffset", void 0);
  31718. __decorate([
  31719. BABYLON.serialize()
  31720. ], Material.prototype, "wireframe", null);
  31721. __decorate([
  31722. BABYLON.serialize()
  31723. ], Material.prototype, "pointsCloud", null);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], Material.prototype, "fillMode", null);
  31727. return Material;
  31728. }());
  31729. BABYLON.Material = Material;
  31730. })(BABYLON || (BABYLON = {}));
  31731. //# sourceMappingURL=babylon.material.js.map
  31732. var BABYLON;
  31733. (function (BABYLON) {
  31734. var UniformBuffer = /** @class */ (function () {
  31735. /**
  31736. * Uniform buffer objects.
  31737. *
  31738. * Handles blocks of uniform on the GPU.
  31739. *
  31740. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31741. *
  31742. * For more information, please refer to :
  31743. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31744. */
  31745. function UniformBuffer(engine, data, dynamic) {
  31746. this._engine = engine;
  31747. this._noUBO = !engine.supportsUniformBuffers;
  31748. this._dynamic = dynamic;
  31749. this._data = data || [];
  31750. this._uniformLocations = {};
  31751. this._uniformSizes = {};
  31752. this._uniformLocationPointer = 0;
  31753. this._needSync = false;
  31754. if (this._noUBO) {
  31755. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31756. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31757. this.updateFloat = this._updateFloatForEffect;
  31758. this.updateFloat2 = this._updateFloat2ForEffect;
  31759. this.updateFloat3 = this._updateFloat3ForEffect;
  31760. this.updateFloat4 = this._updateFloat4ForEffect;
  31761. this.updateMatrix = this._updateMatrixForEffect;
  31762. this.updateVector3 = this._updateVector3ForEffect;
  31763. this.updateVector4 = this._updateVector4ForEffect;
  31764. this.updateColor3 = this._updateColor3ForEffect;
  31765. this.updateColor4 = this._updateColor4ForEffect;
  31766. }
  31767. else {
  31768. this._engine._uniformBuffers.push(this);
  31769. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31770. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31771. this.updateFloat = this._updateFloatForUniform;
  31772. this.updateFloat2 = this._updateFloat2ForUniform;
  31773. this.updateFloat3 = this._updateFloat3ForUniform;
  31774. this.updateFloat4 = this._updateFloat4ForUniform;
  31775. this.updateMatrix = this._updateMatrixForUniform;
  31776. this.updateVector3 = this._updateVector3ForUniform;
  31777. this.updateVector4 = this._updateVector4ForUniform;
  31778. this.updateColor3 = this._updateColor3ForUniform;
  31779. this.updateColor4 = this._updateColor4ForUniform;
  31780. }
  31781. }
  31782. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31783. // Properties
  31784. /**
  31785. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31786. * or just falling back on setUniformXXX calls.
  31787. */
  31788. get: function () {
  31789. return !this._noUBO;
  31790. },
  31791. enumerable: true,
  31792. configurable: true
  31793. });
  31794. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31795. /**
  31796. * Indicates if the WebGL underlying uniform buffer is in sync
  31797. * with the javascript cache data.
  31798. */
  31799. get: function () {
  31800. return !this._needSync;
  31801. },
  31802. enumerable: true,
  31803. configurable: true
  31804. });
  31805. /**
  31806. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31807. * Also, a dynamic UniformBuffer will disable cache verification and always
  31808. * update the underlying WebGL uniform buffer to the GPU.
  31809. */
  31810. UniformBuffer.prototype.isDynamic = function () {
  31811. return this._dynamic !== undefined;
  31812. };
  31813. /**
  31814. * The data cache on JS side.
  31815. */
  31816. UniformBuffer.prototype.getData = function () {
  31817. return this._bufferData;
  31818. };
  31819. /**
  31820. * The underlying WebGL Uniform buffer.
  31821. */
  31822. UniformBuffer.prototype.getBuffer = function () {
  31823. return this._buffer;
  31824. };
  31825. /**
  31826. * std140 layout specifies how to align data within an UBO structure.
  31827. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31828. * for specs.
  31829. */
  31830. UniformBuffer.prototype._fillAlignment = function (size) {
  31831. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31832. // and 4x4 matrices
  31833. // TODO : change if other types are used
  31834. var alignment;
  31835. if (size <= 2) {
  31836. alignment = size;
  31837. }
  31838. else {
  31839. alignment = 4;
  31840. }
  31841. if ((this._uniformLocationPointer % alignment) !== 0) {
  31842. var oldPointer = this._uniformLocationPointer;
  31843. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31844. var diff = this._uniformLocationPointer - oldPointer;
  31845. for (var i = 0; i < diff; i++) {
  31846. this._data.push(0);
  31847. }
  31848. }
  31849. };
  31850. /**
  31851. * Adds an uniform in the buffer.
  31852. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31853. * for the layout to be correct !
  31854. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31855. * @param {number|number[]} size Data size, or data directly.
  31856. */
  31857. UniformBuffer.prototype.addUniform = function (name, size) {
  31858. if (this._noUBO) {
  31859. return;
  31860. }
  31861. if (this._uniformLocations[name] !== undefined) {
  31862. // Already existing uniform
  31863. return;
  31864. }
  31865. // This function must be called in the order of the shader layout !
  31866. // size can be the size of the uniform, or data directly
  31867. var data;
  31868. if (size instanceof Array) {
  31869. data = size;
  31870. size = data.length;
  31871. }
  31872. else {
  31873. size = size;
  31874. data = [];
  31875. // Fill with zeros
  31876. for (var i = 0; i < size; i++) {
  31877. data.push(0);
  31878. }
  31879. }
  31880. this._fillAlignment(size);
  31881. this._uniformSizes[name] = size;
  31882. this._uniformLocations[name] = this._uniformLocationPointer;
  31883. this._uniformLocationPointer += size;
  31884. for (var i = 0; i < size; i++) {
  31885. this._data.push(data[i]);
  31886. }
  31887. this._needSync = true;
  31888. };
  31889. /**
  31890. * Wrapper for addUniform.
  31891. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31892. * @param {Matrix} mat A 4x4 matrix.
  31893. */
  31894. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31895. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31896. };
  31897. /**
  31898. * Wrapper for addUniform.
  31899. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31900. * @param {number} x
  31901. * @param {number} y
  31902. */
  31903. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31904. var temp = [x, y];
  31905. this.addUniform(name, temp);
  31906. };
  31907. /**
  31908. * Wrapper for addUniform.
  31909. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31910. * @param {number} x
  31911. * @param {number} y
  31912. * @param {number} z
  31913. */
  31914. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31915. var temp = [x, y, z];
  31916. this.addUniform(name, temp);
  31917. };
  31918. /**
  31919. * Wrapper for addUniform.
  31920. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31921. * @param {Color3} color
  31922. */
  31923. UniformBuffer.prototype.addColor3 = function (name, color) {
  31924. var temp = new Array();
  31925. color.toArray(temp);
  31926. this.addUniform(name, temp);
  31927. };
  31928. /**
  31929. * Wrapper for addUniform.
  31930. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31931. * @param {Color3} color
  31932. * @param {number} alpha
  31933. */
  31934. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31935. var temp = new Array();
  31936. color.toArray(temp);
  31937. temp.push(alpha);
  31938. this.addUniform(name, temp);
  31939. };
  31940. /**
  31941. * Wrapper for addUniform.
  31942. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31943. * @param {Vector3} vector
  31944. */
  31945. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31946. var temp = new Array();
  31947. vector.toArray(temp);
  31948. this.addUniform(name, temp);
  31949. };
  31950. /**
  31951. * Wrapper for addUniform.
  31952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31953. */
  31954. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31955. this.addUniform(name, 12);
  31956. };
  31957. /**
  31958. * Wrapper for addUniform.
  31959. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31960. */
  31961. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31962. this.addUniform(name, 8);
  31963. };
  31964. /**
  31965. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31966. */
  31967. UniformBuffer.prototype.create = function () {
  31968. if (this._noUBO) {
  31969. return;
  31970. }
  31971. if (this._buffer) {
  31972. return; // nothing to do
  31973. }
  31974. // See spec, alignment must be filled as a vec4
  31975. this._fillAlignment(4);
  31976. this._bufferData = new Float32Array(this._data);
  31977. this._rebuild();
  31978. this._needSync = true;
  31979. };
  31980. UniformBuffer.prototype._rebuild = function () {
  31981. if (this._noUBO) {
  31982. return;
  31983. }
  31984. if (this._dynamic) {
  31985. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31986. }
  31987. else {
  31988. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31989. }
  31990. };
  31991. /**
  31992. * Updates the WebGL Uniform Buffer on the GPU.
  31993. * If the `dynamic` flag is set to true, no cache comparison is done.
  31994. * Otherwise, the buffer will be updated only if the cache differs.
  31995. */
  31996. UniformBuffer.prototype.update = function () {
  31997. if (!this._buffer) {
  31998. this.create();
  31999. return;
  32000. }
  32001. if (!this._dynamic && !this._needSync) {
  32002. return;
  32003. }
  32004. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32005. this._needSync = false;
  32006. };
  32007. /**
  32008. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32009. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32010. * @param {number[]|Float32Array} data Flattened data
  32011. * @param {number} size Size of the data.
  32012. */
  32013. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32014. var location = this._uniformLocations[uniformName];
  32015. if (location === undefined) {
  32016. if (this._buffer) {
  32017. // Cannot add an uniform if the buffer is already created
  32018. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32019. return;
  32020. }
  32021. this.addUniform(uniformName, size);
  32022. location = this._uniformLocations[uniformName];
  32023. }
  32024. if (!this._buffer) {
  32025. this.create();
  32026. }
  32027. if (!this._dynamic) {
  32028. // Cache for static uniform buffers
  32029. var changed = false;
  32030. for (var i = 0; i < size; i++) {
  32031. if (this._bufferData[location + i] !== data[i]) {
  32032. changed = true;
  32033. this._bufferData[location + i] = data[i];
  32034. }
  32035. }
  32036. this._needSync = this._needSync || changed;
  32037. }
  32038. else {
  32039. // No cache for dynamic
  32040. for (var i = 0; i < size; i++) {
  32041. this._bufferData[location + i] = data[i];
  32042. }
  32043. }
  32044. };
  32045. // Update methods
  32046. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32047. // To match std140, matrix must be realigned
  32048. for (var i = 0; i < 3; i++) {
  32049. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32050. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32051. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32052. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32053. }
  32054. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32055. };
  32056. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32057. this._currentEffect.setMatrix3x3(name, matrix);
  32058. };
  32059. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32060. this._currentEffect.setMatrix2x2(name, matrix);
  32061. };
  32062. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32063. // To match std140, matrix must be realigned
  32064. for (var i = 0; i < 2; i++) {
  32065. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32066. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32067. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32068. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32069. }
  32070. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32071. };
  32072. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32073. this._currentEffect.setFloat(name, x);
  32074. };
  32075. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32076. UniformBuffer._tempBuffer[0] = x;
  32077. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32078. };
  32079. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32080. if (suffix === void 0) { suffix = ""; }
  32081. this._currentEffect.setFloat2(name + suffix, x, y);
  32082. };
  32083. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32084. if (suffix === void 0) { suffix = ""; }
  32085. UniformBuffer._tempBuffer[0] = x;
  32086. UniformBuffer._tempBuffer[1] = y;
  32087. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32088. };
  32089. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32090. if (suffix === void 0) { suffix = ""; }
  32091. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32092. };
  32093. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32094. if (suffix === void 0) { suffix = ""; }
  32095. UniformBuffer._tempBuffer[0] = x;
  32096. UniformBuffer._tempBuffer[1] = y;
  32097. UniformBuffer._tempBuffer[2] = z;
  32098. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32099. };
  32100. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32101. if (suffix === void 0) { suffix = ""; }
  32102. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32103. };
  32104. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32105. if (suffix === void 0) { suffix = ""; }
  32106. UniformBuffer._tempBuffer[0] = x;
  32107. UniformBuffer._tempBuffer[1] = y;
  32108. UniformBuffer._tempBuffer[2] = z;
  32109. UniformBuffer._tempBuffer[3] = w;
  32110. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32111. };
  32112. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32113. this._currentEffect.setMatrix(name, mat);
  32114. };
  32115. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32116. this.updateUniform(name, mat.toArray(), 16);
  32117. };
  32118. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32119. this._currentEffect.setVector3(name, vector);
  32120. };
  32121. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32122. vector.toArray(UniformBuffer._tempBuffer);
  32123. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32124. };
  32125. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32126. this._currentEffect.setVector4(name, vector);
  32127. };
  32128. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32129. vector.toArray(UniformBuffer._tempBuffer);
  32130. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32131. };
  32132. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32133. if (suffix === void 0) { suffix = ""; }
  32134. this._currentEffect.setColor3(name + suffix, color);
  32135. };
  32136. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. color.toArray(UniformBuffer._tempBuffer);
  32139. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32140. };
  32141. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32142. if (suffix === void 0) { suffix = ""; }
  32143. this._currentEffect.setColor4(name + suffix, color, alpha);
  32144. };
  32145. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32146. if (suffix === void 0) { suffix = ""; }
  32147. color.toArray(UniformBuffer._tempBuffer);
  32148. UniformBuffer._tempBuffer[3] = alpha;
  32149. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32150. };
  32151. /**
  32152. * Sets a sampler uniform on the effect.
  32153. * @param {string} name Name of the sampler.
  32154. * @param {Texture} texture
  32155. */
  32156. UniformBuffer.prototype.setTexture = function (name, texture) {
  32157. this._currentEffect.setTexture(name, texture);
  32158. };
  32159. /**
  32160. * Directly updates the value of the uniform in the cache AND on the GPU.
  32161. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32162. * @param {number[]|Float32Array} data Flattened data
  32163. */
  32164. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32165. this.updateUniform(uniformName, data, data.length);
  32166. this.update();
  32167. };
  32168. /**
  32169. * Binds this uniform buffer to an effect.
  32170. * @param {Effect} effect
  32171. * @param {string} name Name of the uniform block in the shader.
  32172. */
  32173. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32174. this._currentEffect = effect;
  32175. if (this._noUBO || !this._buffer) {
  32176. return;
  32177. }
  32178. effect.bindUniformBuffer(this._buffer, name);
  32179. };
  32180. /**
  32181. * Disposes the uniform buffer.
  32182. */
  32183. UniformBuffer.prototype.dispose = function () {
  32184. if (this._noUBO) {
  32185. return;
  32186. }
  32187. var index = this._engine._uniformBuffers.indexOf(this);
  32188. if (index !== -1) {
  32189. this._engine._uniformBuffers.splice(index, 1);
  32190. }
  32191. if (!this._buffer) {
  32192. return;
  32193. }
  32194. if (this._engine._releaseBuffer(this._buffer)) {
  32195. this._buffer = null;
  32196. }
  32197. };
  32198. // Pool for avoiding memory leaks
  32199. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32200. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32201. return UniformBuffer;
  32202. }());
  32203. BABYLON.UniformBuffer = UniformBuffer;
  32204. })(BABYLON || (BABYLON = {}));
  32205. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32206. var BABYLON;
  32207. (function (BABYLON) {
  32208. var VertexData = /** @class */ (function () {
  32209. function VertexData() {
  32210. }
  32211. VertexData.prototype.set = function (data, kind) {
  32212. switch (kind) {
  32213. case BABYLON.VertexBuffer.PositionKind:
  32214. this.positions = data;
  32215. break;
  32216. case BABYLON.VertexBuffer.NormalKind:
  32217. this.normals = data;
  32218. break;
  32219. case BABYLON.VertexBuffer.TangentKind:
  32220. this.tangents = data;
  32221. break;
  32222. case BABYLON.VertexBuffer.UVKind:
  32223. this.uvs = data;
  32224. break;
  32225. case BABYLON.VertexBuffer.UV2Kind:
  32226. this.uvs2 = data;
  32227. break;
  32228. case BABYLON.VertexBuffer.UV3Kind:
  32229. this.uvs3 = data;
  32230. break;
  32231. case BABYLON.VertexBuffer.UV4Kind:
  32232. this.uvs4 = data;
  32233. break;
  32234. case BABYLON.VertexBuffer.UV5Kind:
  32235. this.uvs5 = data;
  32236. break;
  32237. case BABYLON.VertexBuffer.UV6Kind:
  32238. this.uvs6 = data;
  32239. break;
  32240. case BABYLON.VertexBuffer.ColorKind:
  32241. this.colors = data;
  32242. break;
  32243. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32244. this.matricesIndices = data;
  32245. break;
  32246. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32247. this.matricesWeights = data;
  32248. break;
  32249. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32250. this.matricesIndicesExtra = data;
  32251. break;
  32252. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32253. this.matricesWeightsExtra = data;
  32254. break;
  32255. }
  32256. };
  32257. /**
  32258. * Associates the vertexData to the passed Mesh.
  32259. * Sets it as updatable or not (default `false`).
  32260. * Returns the VertexData.
  32261. */
  32262. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32263. this._applyTo(mesh, updatable);
  32264. return this;
  32265. };
  32266. /**
  32267. * Associates the vertexData to the passed Geometry.
  32268. * Sets it as updatable or not (default `false`).
  32269. * Returns the VertexData.
  32270. */
  32271. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32272. this._applyTo(geometry, updatable);
  32273. return this;
  32274. };
  32275. /**
  32276. * Updates the associated mesh.
  32277. * Returns the VertexData.
  32278. */
  32279. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32280. this._update(mesh);
  32281. return this;
  32282. };
  32283. /**
  32284. * Updates the associated geometry.
  32285. * Returns the VertexData.
  32286. */
  32287. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32288. this._update(geometry);
  32289. return this;
  32290. };
  32291. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32292. if (updatable === void 0) { updatable = false; }
  32293. if (this.positions) {
  32294. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32295. }
  32296. if (this.normals) {
  32297. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32298. }
  32299. if (this.tangents) {
  32300. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32301. }
  32302. if (this.uvs) {
  32303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32304. }
  32305. if (this.uvs2) {
  32306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32307. }
  32308. if (this.uvs3) {
  32309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32310. }
  32311. if (this.uvs4) {
  32312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32313. }
  32314. if (this.uvs5) {
  32315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32316. }
  32317. if (this.uvs6) {
  32318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32319. }
  32320. if (this.colors) {
  32321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32322. }
  32323. if (this.matricesIndices) {
  32324. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32325. }
  32326. if (this.matricesWeights) {
  32327. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32328. }
  32329. if (this.matricesIndicesExtra) {
  32330. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32331. }
  32332. if (this.matricesWeightsExtra) {
  32333. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32334. }
  32335. if (this.indices) {
  32336. meshOrGeometry.setIndices(this.indices, null, updatable);
  32337. }
  32338. return this;
  32339. };
  32340. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32341. if (this.positions) {
  32342. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32343. }
  32344. if (this.normals) {
  32345. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32346. }
  32347. if (this.tangents) {
  32348. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32349. }
  32350. if (this.uvs) {
  32351. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32352. }
  32353. if (this.uvs2) {
  32354. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32355. }
  32356. if (this.uvs3) {
  32357. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32358. }
  32359. if (this.uvs4) {
  32360. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32361. }
  32362. if (this.uvs5) {
  32363. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32364. }
  32365. if (this.uvs6) {
  32366. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32367. }
  32368. if (this.colors) {
  32369. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32370. }
  32371. if (this.matricesIndices) {
  32372. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32373. }
  32374. if (this.matricesWeights) {
  32375. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32376. }
  32377. if (this.matricesIndicesExtra) {
  32378. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32379. }
  32380. if (this.matricesWeightsExtra) {
  32381. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32382. }
  32383. if (this.indices) {
  32384. meshOrGeometry.setIndices(this.indices, null);
  32385. }
  32386. return this;
  32387. };
  32388. /**
  32389. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32390. * Returns the VertexData.
  32391. */
  32392. VertexData.prototype.transform = function (matrix) {
  32393. var transformed = BABYLON.Vector3.Zero();
  32394. var index;
  32395. if (this.positions) {
  32396. var position = BABYLON.Vector3.Zero();
  32397. for (index = 0; index < this.positions.length; index += 3) {
  32398. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32399. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32400. this.positions[index] = transformed.x;
  32401. this.positions[index + 1] = transformed.y;
  32402. this.positions[index + 2] = transformed.z;
  32403. }
  32404. }
  32405. if (this.normals) {
  32406. var normal = BABYLON.Vector3.Zero();
  32407. for (index = 0; index < this.normals.length; index += 3) {
  32408. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32409. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32410. this.normals[index] = transformed.x;
  32411. this.normals[index + 1] = transformed.y;
  32412. this.normals[index + 2] = transformed.z;
  32413. }
  32414. }
  32415. if (this.tangents) {
  32416. var tangent = BABYLON.Vector4.Zero();
  32417. var tangentTransformed = BABYLON.Vector4.Zero();
  32418. for (index = 0; index < this.tangents.length; index += 4) {
  32419. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32420. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32421. this.tangents[index] = tangentTransformed.x;
  32422. this.tangents[index + 1] = tangentTransformed.y;
  32423. this.tangents[index + 2] = tangentTransformed.z;
  32424. this.tangents[index + 3] = tangentTransformed.w;
  32425. }
  32426. }
  32427. return this;
  32428. };
  32429. /**
  32430. * Merges the passed VertexData into the current one.
  32431. * Returns the modified VertexData.
  32432. */
  32433. VertexData.prototype.merge = function (other) {
  32434. this._validate();
  32435. other._validate();
  32436. if (!this.normals !== !other.normals ||
  32437. !this.tangents !== !other.tangents ||
  32438. !this.uvs !== !other.uvs ||
  32439. !this.uvs2 !== !other.uvs2 ||
  32440. !this.uvs3 !== !other.uvs3 ||
  32441. !this.uvs4 !== !other.uvs4 ||
  32442. !this.uvs5 !== !other.uvs5 ||
  32443. !this.uvs6 !== !other.uvs6 ||
  32444. !this.colors !== !other.colors ||
  32445. !this.matricesIndices !== !other.matricesIndices ||
  32446. !this.matricesWeights !== !other.matricesWeights ||
  32447. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32448. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32449. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32450. }
  32451. if (other.indices) {
  32452. if (!this.indices) {
  32453. this.indices = [];
  32454. }
  32455. var offset = this.positions ? this.positions.length / 3 : 0;
  32456. for (var index = 0; index < other.indices.length; index++) {
  32457. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32458. this.indices.push(other.indices[index] + offset);
  32459. }
  32460. }
  32461. this.positions = this._mergeElement(this.positions, other.positions);
  32462. this.normals = this._mergeElement(this.normals, other.normals);
  32463. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32464. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32465. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32466. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32467. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32468. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32469. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32470. this.colors = this._mergeElement(this.colors, other.colors);
  32471. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32472. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32473. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32474. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32475. return this;
  32476. };
  32477. VertexData.prototype._mergeElement = function (source, other) {
  32478. if (!source) {
  32479. return other;
  32480. }
  32481. if (!other) {
  32482. return source;
  32483. }
  32484. var len = other.length + source.length;
  32485. var isSrcTypedArray = source instanceof Float32Array;
  32486. var isOthTypedArray = other instanceof Float32Array;
  32487. // use non-loop method when the source is Float32Array
  32488. if (isSrcTypedArray) {
  32489. var ret32 = new Float32Array(len);
  32490. ret32.set(source);
  32491. ret32.set(other, source.length);
  32492. return ret32;
  32493. // source is number[], when other is also use concat
  32494. }
  32495. else if (!isOthTypedArray) {
  32496. return source.concat(other);
  32497. // source is a number[], but other is a Float32Array, loop required
  32498. }
  32499. else {
  32500. var ret = source.slice(0); // copy source to a separate array
  32501. for (var i = 0, len = other.length; i < len; i++) {
  32502. ret.push(other[i]);
  32503. }
  32504. return ret;
  32505. }
  32506. };
  32507. VertexData.prototype._validate = function () {
  32508. if (!this.positions) {
  32509. throw new Error("Positions are required");
  32510. }
  32511. var getElementCount = function (kind, values) {
  32512. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32513. if ((values.length % stride) !== 0) {
  32514. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32515. }
  32516. return values.length / stride;
  32517. };
  32518. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32519. var validateElementCount = function (kind, values) {
  32520. var elementCount = getElementCount(kind, values);
  32521. if (elementCount !== positionsElementCount) {
  32522. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32523. }
  32524. };
  32525. if (this.normals)
  32526. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32527. if (this.tangents)
  32528. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32529. if (this.uvs)
  32530. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32531. if (this.uvs2)
  32532. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32533. if (this.uvs3)
  32534. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32535. if (this.uvs4)
  32536. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32537. if (this.uvs5)
  32538. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32539. if (this.uvs6)
  32540. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32541. if (this.colors)
  32542. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32543. if (this.matricesIndices)
  32544. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32545. if (this.matricesWeights)
  32546. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32547. if (this.matricesIndicesExtra)
  32548. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32549. if (this.matricesWeightsExtra)
  32550. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32551. };
  32552. /**
  32553. * Serializes the VertexData.
  32554. * Returns a serialized object.
  32555. */
  32556. VertexData.prototype.serialize = function () {
  32557. var serializationObject = this.serialize();
  32558. if (this.positions) {
  32559. serializationObject.positions = this.positions;
  32560. }
  32561. if (this.normals) {
  32562. serializationObject.normals = this.normals;
  32563. }
  32564. if (this.tangents) {
  32565. serializationObject.tangents = this.tangents;
  32566. }
  32567. if (this.uvs) {
  32568. serializationObject.uvs = this.uvs;
  32569. }
  32570. if (this.uvs2) {
  32571. serializationObject.uvs2 = this.uvs2;
  32572. }
  32573. if (this.uvs3) {
  32574. serializationObject.uvs3 = this.uvs3;
  32575. }
  32576. if (this.uvs4) {
  32577. serializationObject.uvs4 = this.uvs4;
  32578. }
  32579. if (this.uvs5) {
  32580. serializationObject.uvs5 = this.uvs5;
  32581. }
  32582. if (this.uvs6) {
  32583. serializationObject.uvs6 = this.uvs6;
  32584. }
  32585. if (this.colors) {
  32586. serializationObject.colors = this.colors;
  32587. }
  32588. if (this.matricesIndices) {
  32589. serializationObject.matricesIndices = this.matricesIndices;
  32590. serializationObject.matricesIndices._isExpanded = true;
  32591. }
  32592. if (this.matricesWeights) {
  32593. serializationObject.matricesWeights = this.matricesWeights;
  32594. }
  32595. if (this.matricesIndicesExtra) {
  32596. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32597. serializationObject.matricesIndicesExtra._isExpanded = true;
  32598. }
  32599. if (this.matricesWeightsExtra) {
  32600. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32601. }
  32602. serializationObject.indices = this.indices;
  32603. return serializationObject;
  32604. };
  32605. // Statics
  32606. /**
  32607. * Returns the object VertexData associated to the passed mesh.
  32608. */
  32609. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32610. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32611. };
  32612. /**
  32613. * Returns the object VertexData associated to the passed geometry.
  32614. */
  32615. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32616. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32617. };
  32618. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32619. var result = new VertexData();
  32620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32621. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32622. }
  32623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32624. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32625. }
  32626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32627. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32628. }
  32629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32630. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32631. }
  32632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32633. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32634. }
  32635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32636. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32637. }
  32638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32639. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32640. }
  32641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32642. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32643. }
  32644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32645. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32646. }
  32647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32648. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32649. }
  32650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32651. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32652. }
  32653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32654. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32655. }
  32656. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32657. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32658. }
  32659. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32660. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32661. }
  32662. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32663. return result;
  32664. };
  32665. /**
  32666. * Creates the vertexData of the Ribbon.
  32667. */
  32668. VertexData.CreateRibbon = function (options) {
  32669. var pathArray = options.pathArray;
  32670. var closeArray = options.closeArray || false;
  32671. var closePath = options.closePath || false;
  32672. var invertUV = options.invertUV || false;
  32673. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32674. var offset = options.offset || defaultOffset;
  32675. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32677. var customUV = options.uvs;
  32678. var customColors = options.colors;
  32679. var positions = [];
  32680. var indices = [];
  32681. var normals = [];
  32682. var uvs = [];
  32683. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32684. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32685. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32686. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32687. var minlg; // minimal length among all paths from pathArray
  32688. var lg = []; // array of path lengths : nb of vertex per path
  32689. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32690. var p; // path iterator
  32691. var i; // point iterator
  32692. var j; // point iterator
  32693. // if single path in pathArray
  32694. if (pathArray.length < 2) {
  32695. var ar1 = [];
  32696. var ar2 = [];
  32697. for (i = 0; i < pathArray[0].length - offset; i++) {
  32698. ar1.push(pathArray[0][i]);
  32699. ar2.push(pathArray[0][i + offset]);
  32700. }
  32701. pathArray = [ar1, ar2];
  32702. }
  32703. // positions and horizontal distances (u)
  32704. var idc = 0;
  32705. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32706. var path;
  32707. var l;
  32708. minlg = pathArray[0].length;
  32709. var vectlg;
  32710. var dist;
  32711. for (p = 0; p < pathArray.length; p++) {
  32712. uTotalDistance[p] = 0;
  32713. us[p] = [0];
  32714. path = pathArray[p];
  32715. l = path.length;
  32716. minlg = (minlg < l) ? minlg : l;
  32717. j = 0;
  32718. while (j < l) {
  32719. positions.push(path[j].x, path[j].y, path[j].z);
  32720. if (j > 0) {
  32721. vectlg = path[j].subtract(path[j - 1]).length();
  32722. dist = vectlg + uTotalDistance[p];
  32723. us[p].push(dist);
  32724. uTotalDistance[p] = dist;
  32725. }
  32726. j++;
  32727. }
  32728. if (closePath) {
  32729. j--;
  32730. positions.push(path[0].x, path[0].y, path[0].z);
  32731. vectlg = path[j].subtract(path[0]).length();
  32732. dist = vectlg + uTotalDistance[p];
  32733. us[p].push(dist);
  32734. uTotalDistance[p] = dist;
  32735. }
  32736. lg[p] = l + closePathCorr;
  32737. idx[p] = idc;
  32738. idc += (l + closePathCorr);
  32739. }
  32740. // vertical distances (v)
  32741. var path1;
  32742. var path2;
  32743. var vertex1 = null;
  32744. var vertex2 = null;
  32745. for (i = 0; i < minlg + closePathCorr; i++) {
  32746. vTotalDistance[i] = 0;
  32747. vs[i] = [0];
  32748. for (p = 0; p < pathArray.length - 1; p++) {
  32749. path1 = pathArray[p];
  32750. path2 = pathArray[p + 1];
  32751. if (i === minlg) {
  32752. vertex1 = path1[0];
  32753. vertex2 = path2[0];
  32754. }
  32755. else {
  32756. vertex1 = path1[i];
  32757. vertex2 = path2[i];
  32758. }
  32759. vectlg = vertex2.subtract(vertex1).length();
  32760. dist = vectlg + vTotalDistance[i];
  32761. vs[i].push(dist);
  32762. vTotalDistance[i] = dist;
  32763. }
  32764. if (closeArray && vertex2 && vertex1) {
  32765. path1 = pathArray[p];
  32766. path2 = pathArray[0];
  32767. if (i === minlg) {
  32768. vertex2 = path2[0];
  32769. }
  32770. vectlg = vertex2.subtract(vertex1).length();
  32771. dist = vectlg + vTotalDistance[i];
  32772. vTotalDistance[i] = dist;
  32773. }
  32774. }
  32775. // uvs
  32776. var u;
  32777. var v;
  32778. if (customUV) {
  32779. for (p = 0; p < customUV.length; p++) {
  32780. uvs.push(customUV[p].x, customUV[p].y);
  32781. }
  32782. }
  32783. else {
  32784. for (p = 0; p < pathArray.length; p++) {
  32785. for (i = 0; i < minlg + closePathCorr; i++) {
  32786. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32787. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32788. if (invertUV) {
  32789. uvs.push(v, u);
  32790. }
  32791. else {
  32792. uvs.push(u, v);
  32793. }
  32794. }
  32795. }
  32796. }
  32797. // indices
  32798. p = 0; // path index
  32799. var pi = 0; // positions array index
  32800. var l1 = lg[p] - 1; // path1 length
  32801. var l2 = lg[p + 1] - 1; // path2 length
  32802. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32803. var shft = idx[1] - idx[0]; // shift
  32804. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32805. while (pi <= min && p < path1nb) {
  32806. // 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
  32807. indices.push(pi, pi + shft, pi + 1);
  32808. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32809. pi += 1;
  32810. if (pi === min) {
  32811. p++;
  32812. if (p === lg.length - 1) {
  32813. shft = idx[0] - idx[p];
  32814. l1 = lg[p] - 1;
  32815. l2 = lg[0] - 1;
  32816. }
  32817. else {
  32818. shft = idx[p + 1] - idx[p];
  32819. l1 = lg[p] - 1;
  32820. l2 = lg[p + 1] - 1;
  32821. }
  32822. pi = idx[p];
  32823. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32824. }
  32825. }
  32826. // normals
  32827. VertexData.ComputeNormals(positions, indices, normals);
  32828. if (closePath) {
  32829. var indexFirst = 0;
  32830. var indexLast = 0;
  32831. for (p = 0; p < pathArray.length; p++) {
  32832. indexFirst = idx[p] * 3;
  32833. if (p + 1 < pathArray.length) {
  32834. indexLast = (idx[p + 1] - 1) * 3;
  32835. }
  32836. else {
  32837. indexLast = normals.length - 3;
  32838. }
  32839. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32840. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32841. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32842. normals[indexLast] = normals[indexFirst];
  32843. normals[indexLast + 1] = normals[indexFirst + 1];
  32844. normals[indexLast + 2] = normals[indexFirst + 2];
  32845. }
  32846. }
  32847. // sides
  32848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32849. // Colors
  32850. var colors = null;
  32851. if (customColors) {
  32852. colors = new Float32Array(customColors.length * 4);
  32853. for (var c = 0; c < customColors.length; c++) {
  32854. colors[c * 4] = customColors[c].r;
  32855. colors[c * 4 + 1] = customColors[c].g;
  32856. colors[c * 4 + 2] = customColors[c].b;
  32857. colors[c * 4 + 3] = customColors[c].a;
  32858. }
  32859. }
  32860. // Result
  32861. var vertexData = new VertexData();
  32862. var positions32 = new Float32Array(positions);
  32863. var normals32 = new Float32Array(normals);
  32864. var uvs32 = new Float32Array(uvs);
  32865. vertexData.indices = indices;
  32866. vertexData.positions = positions32;
  32867. vertexData.normals = normals32;
  32868. vertexData.uvs = uvs32;
  32869. if (colors) {
  32870. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32871. }
  32872. if (closePath) {
  32873. vertexData._idx = idx;
  32874. }
  32875. return vertexData;
  32876. };
  32877. /**
  32878. * Creates the VertexData of the Box.
  32879. */
  32880. VertexData.CreateBox = function (options) {
  32881. var normalsSource = [
  32882. new BABYLON.Vector3(0, 0, 1),
  32883. new BABYLON.Vector3(0, 0, -1),
  32884. new BABYLON.Vector3(1, 0, 0),
  32885. new BABYLON.Vector3(-1, 0, 0),
  32886. new BABYLON.Vector3(0, 1, 0),
  32887. new BABYLON.Vector3(0, -1, 0)
  32888. ];
  32889. var indices = [];
  32890. var positions = [];
  32891. var normals = [];
  32892. var uvs = [];
  32893. var width = options.width || options.size || 1;
  32894. var height = options.height || options.size || 1;
  32895. var depth = options.depth || options.size || 1;
  32896. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32897. var faceUV = options.faceUV || new Array(6);
  32898. var faceColors = options.faceColors;
  32899. var colors = [];
  32900. // default face colors and UV if undefined
  32901. for (var f = 0; f < 6; f++) {
  32902. if (faceUV[f] === undefined) {
  32903. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32904. }
  32905. if (faceColors && faceColors[f] === undefined) {
  32906. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32907. }
  32908. }
  32909. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32910. // Create each face in turn.
  32911. for (var index = 0; index < normalsSource.length; index++) {
  32912. var normal = normalsSource[index];
  32913. // Get two vectors perpendicular to the face normal and to each other.
  32914. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32915. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32916. // Six indices (two triangles) per face.
  32917. var verticesLength = positions.length / 3;
  32918. indices.push(verticesLength);
  32919. indices.push(verticesLength + 1);
  32920. indices.push(verticesLength + 2);
  32921. indices.push(verticesLength);
  32922. indices.push(verticesLength + 2);
  32923. indices.push(verticesLength + 3);
  32924. // Four vertices per face.
  32925. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32926. positions.push(vertex.x, vertex.y, vertex.z);
  32927. normals.push(normal.x, normal.y, normal.z);
  32928. uvs.push(faceUV[index].z, faceUV[index].w);
  32929. if (faceColors) {
  32930. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32931. }
  32932. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32933. positions.push(vertex.x, vertex.y, vertex.z);
  32934. normals.push(normal.x, normal.y, normal.z);
  32935. uvs.push(faceUV[index].x, faceUV[index].w);
  32936. if (faceColors) {
  32937. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32938. }
  32939. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32940. positions.push(vertex.x, vertex.y, vertex.z);
  32941. normals.push(normal.x, normal.y, normal.z);
  32942. uvs.push(faceUV[index].x, faceUV[index].y);
  32943. if (faceColors) {
  32944. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32945. }
  32946. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32947. positions.push(vertex.x, vertex.y, vertex.z);
  32948. normals.push(normal.x, normal.y, normal.z);
  32949. uvs.push(faceUV[index].z, faceUV[index].y);
  32950. if (faceColors) {
  32951. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32952. }
  32953. }
  32954. // sides
  32955. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32956. // Result
  32957. var vertexData = new VertexData();
  32958. vertexData.indices = indices;
  32959. vertexData.positions = positions;
  32960. vertexData.normals = normals;
  32961. vertexData.uvs = uvs;
  32962. if (faceColors) {
  32963. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32964. vertexData.colors = totalColors;
  32965. }
  32966. return vertexData;
  32967. };
  32968. /**
  32969. * Creates the VertexData of the Sphere.
  32970. */
  32971. VertexData.CreateSphere = function (options) {
  32972. var segments = options.segments || 32;
  32973. var diameterX = options.diameterX || options.diameter || 1;
  32974. var diameterY = options.diameterY || options.diameter || 1;
  32975. var diameterZ = options.diameterZ || options.diameter || 1;
  32976. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32977. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32978. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32979. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32980. var totalZRotationSteps = 2 + segments;
  32981. var totalYRotationSteps = 2 * totalZRotationSteps;
  32982. var indices = [];
  32983. var positions = [];
  32984. var normals = [];
  32985. var uvs = [];
  32986. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32987. var normalizedZ = zRotationStep / totalZRotationSteps;
  32988. var angleZ = normalizedZ * Math.PI * slice;
  32989. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32990. var normalizedY = yRotationStep / totalYRotationSteps;
  32991. var angleY = normalizedY * Math.PI * 2 * arc;
  32992. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32993. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32994. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32995. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32996. var vertex = complete.multiply(radius);
  32997. var normal = complete.divide(radius).normalize();
  32998. positions.push(vertex.x, vertex.y, vertex.z);
  32999. normals.push(normal.x, normal.y, normal.z);
  33000. uvs.push(normalizedY, normalizedZ);
  33001. }
  33002. if (zRotationStep > 0) {
  33003. var verticesCount = positions.length / 3;
  33004. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33005. indices.push((firstIndex));
  33006. indices.push((firstIndex + 1));
  33007. indices.push(firstIndex + totalYRotationSteps + 1);
  33008. indices.push((firstIndex + totalYRotationSteps + 1));
  33009. indices.push((firstIndex + 1));
  33010. indices.push((firstIndex + totalYRotationSteps + 2));
  33011. }
  33012. }
  33013. }
  33014. // Sides
  33015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33016. // Result
  33017. var vertexData = new VertexData();
  33018. vertexData.indices = indices;
  33019. vertexData.positions = positions;
  33020. vertexData.normals = normals;
  33021. vertexData.uvs = uvs;
  33022. return vertexData;
  33023. };
  33024. /**
  33025. * Creates the VertexData of the Cylinder or Cone.
  33026. */
  33027. VertexData.CreateCylinder = function (options) {
  33028. var height = options.height || 2;
  33029. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33030. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33031. var tessellation = options.tessellation || 24;
  33032. var subdivisions = options.subdivisions || 1;
  33033. var hasRings = options.hasRings ? true : false;
  33034. var enclose = options.enclose ? true : false;
  33035. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33037. var faceUV = options.faceUV || new Array(3);
  33038. var faceColors = options.faceColors;
  33039. // default face colors and UV if undefined
  33040. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33041. var ringNb = (hasRings) ? subdivisions : 1;
  33042. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33043. var f;
  33044. for (f = 0; f < surfaceNb; f++) {
  33045. if (faceColors && faceColors[f] === undefined) {
  33046. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33047. }
  33048. }
  33049. for (f = 0; f < surfaceNb; f++) {
  33050. if (faceUV && faceUV[f] === undefined) {
  33051. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33052. }
  33053. }
  33054. var indices = new Array();
  33055. var positions = new Array();
  33056. var normals = new Array();
  33057. var uvs = new Array();
  33058. var colors = new Array();
  33059. var angle_step = Math.PI * 2 * arc / tessellation;
  33060. var angle;
  33061. var h;
  33062. var radius;
  33063. var tan = (diameterBottom - diameterTop) / 2 / height;
  33064. var ringVertex = BABYLON.Vector3.Zero();
  33065. var ringNormal = BABYLON.Vector3.Zero();
  33066. var ringFirstVertex = BABYLON.Vector3.Zero();
  33067. var ringFirstNormal = BABYLON.Vector3.Zero();
  33068. var quadNormal = BABYLON.Vector3.Zero();
  33069. var Y = BABYLON.Axis.Y;
  33070. // positions, normals, uvs
  33071. var i;
  33072. var j;
  33073. var r;
  33074. var ringIdx = 1;
  33075. var s = 1; // surface index
  33076. var cs = 0;
  33077. var v = 0;
  33078. for (i = 0; i <= subdivisions; i++) {
  33079. h = i / subdivisions;
  33080. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33081. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33082. for (r = 0; r < ringIdx; r++) {
  33083. if (hasRings) {
  33084. s += r;
  33085. }
  33086. if (enclose) {
  33087. s += 2 * r;
  33088. }
  33089. for (j = 0; j <= tessellation; j++) {
  33090. angle = j * angle_step;
  33091. // position
  33092. ringVertex.x = Math.cos(-angle) * radius;
  33093. ringVertex.y = -height / 2 + h * height;
  33094. ringVertex.z = Math.sin(-angle) * radius;
  33095. // normal
  33096. if (diameterTop === 0 && i === subdivisions) {
  33097. // if no top cap, reuse former normals
  33098. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33099. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33100. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33101. }
  33102. else {
  33103. ringNormal.x = ringVertex.x;
  33104. ringNormal.z = ringVertex.z;
  33105. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33106. ringNormal.normalize();
  33107. }
  33108. // keep first ring vertex values for enclose
  33109. if (j === 0) {
  33110. ringFirstVertex.copyFrom(ringVertex);
  33111. ringFirstNormal.copyFrom(ringNormal);
  33112. }
  33113. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33114. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33115. if (hasRings) {
  33116. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33117. }
  33118. else {
  33119. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33120. }
  33121. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33122. if (faceColors) {
  33123. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33124. }
  33125. }
  33126. // if enclose, add four vertices and their dedicated normals
  33127. if (arc !== 1 && enclose) {
  33128. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33129. positions.push(0, ringVertex.y, 0);
  33130. positions.push(0, ringVertex.y, 0);
  33131. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33132. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33133. quadNormal.normalize();
  33134. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33135. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33136. quadNormal.normalize();
  33137. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33138. if (hasRings) {
  33139. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33140. }
  33141. else {
  33142. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33143. }
  33144. uvs.push(faceUV[s + 1].x, v);
  33145. uvs.push(faceUV[s + 1].z, v);
  33146. if (hasRings) {
  33147. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33148. }
  33149. else {
  33150. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33151. }
  33152. uvs.push(faceUV[s + 2].x, v);
  33153. uvs.push(faceUV[s + 2].z, v);
  33154. if (faceColors) {
  33155. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33156. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33157. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33158. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33159. }
  33160. }
  33161. if (cs !== s) {
  33162. cs = s;
  33163. }
  33164. }
  33165. }
  33166. // indices
  33167. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33168. var s;
  33169. i = 0;
  33170. for (s = 0; s < subdivisions; s++) {
  33171. var i0 = 0;
  33172. var i1 = 0;
  33173. var i2 = 0;
  33174. var i3 = 0;
  33175. for (j = 0; j < tessellation; j++) {
  33176. i0 = i * (e + 1) + j;
  33177. i1 = (i + 1) * (e + 1) + j;
  33178. i2 = i * (e + 1) + (j + 1);
  33179. i3 = (i + 1) * (e + 1) + (j + 1);
  33180. indices.push(i0, i1, i2);
  33181. indices.push(i3, i2, i1);
  33182. }
  33183. if (arc !== 1 && enclose) {
  33184. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33185. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33186. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33187. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33188. }
  33189. i = (hasRings) ? (i + 2) : (i + 1);
  33190. }
  33191. // Caps
  33192. var createCylinderCap = function (isTop) {
  33193. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33194. if (radius === 0) {
  33195. return;
  33196. }
  33197. // Cap positions, normals & uvs
  33198. var angle;
  33199. var circleVector;
  33200. var i;
  33201. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33202. var c = null;
  33203. if (faceColors) {
  33204. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33205. }
  33206. // cap center
  33207. var vbase = positions.length / 3;
  33208. var offset = isTop ? height / 2 : -height / 2;
  33209. var center = new BABYLON.Vector3(0, offset, 0);
  33210. positions.push(center.x, center.y, center.z);
  33211. normals.push(0, isTop ? 1 : -1, 0);
  33212. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33213. if (c) {
  33214. colors.push(c.r, c.g, c.b, c.a);
  33215. }
  33216. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33217. for (i = 0; i <= tessellation; i++) {
  33218. angle = Math.PI * 2 * i * arc / tessellation;
  33219. var cos = Math.cos(-angle);
  33220. var sin = Math.sin(-angle);
  33221. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33222. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33223. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33224. normals.push(0, isTop ? 1 : -1, 0);
  33225. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33226. if (c) {
  33227. colors.push(c.r, c.g, c.b, c.a);
  33228. }
  33229. }
  33230. // Cap indices
  33231. for (i = 0; i < tessellation; i++) {
  33232. if (!isTop) {
  33233. indices.push(vbase);
  33234. indices.push(vbase + (i + 1));
  33235. indices.push(vbase + (i + 2));
  33236. }
  33237. else {
  33238. indices.push(vbase);
  33239. indices.push(vbase + (i + 2));
  33240. indices.push(vbase + (i + 1));
  33241. }
  33242. }
  33243. };
  33244. // add caps to geometry
  33245. createCylinderCap(false);
  33246. createCylinderCap(true);
  33247. // Sides
  33248. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33249. var vertexData = new VertexData();
  33250. vertexData.indices = indices;
  33251. vertexData.positions = positions;
  33252. vertexData.normals = normals;
  33253. vertexData.uvs = uvs;
  33254. if (faceColors) {
  33255. vertexData.colors = colors;
  33256. }
  33257. return vertexData;
  33258. };
  33259. /**
  33260. * Creates the VertexData of the Torus.
  33261. */
  33262. VertexData.CreateTorus = function (options) {
  33263. var indices = [];
  33264. var positions = [];
  33265. var normals = [];
  33266. var uvs = [];
  33267. var diameter = options.diameter || 1;
  33268. var thickness = options.thickness || 0.5;
  33269. var tessellation = options.tessellation || 16;
  33270. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33271. var stride = tessellation + 1;
  33272. for (var i = 0; i <= tessellation; i++) {
  33273. var u = i / tessellation;
  33274. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33275. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33276. for (var j = 0; j <= tessellation; j++) {
  33277. var v = 1 - j / tessellation;
  33278. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33279. var dx = Math.cos(innerAngle);
  33280. var dy = Math.sin(innerAngle);
  33281. // Create a vertex.
  33282. var normal = new BABYLON.Vector3(dx, dy, 0);
  33283. var position = normal.scale(thickness / 2);
  33284. var textureCoordinate = new BABYLON.Vector2(u, v);
  33285. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33286. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33287. positions.push(position.x, position.y, position.z);
  33288. normals.push(normal.x, normal.y, normal.z);
  33289. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33290. // And create indices for two triangles.
  33291. var nextI = (i + 1) % stride;
  33292. var nextJ = (j + 1) % stride;
  33293. indices.push(i * stride + j);
  33294. indices.push(i * stride + nextJ);
  33295. indices.push(nextI * stride + j);
  33296. indices.push(i * stride + nextJ);
  33297. indices.push(nextI * stride + nextJ);
  33298. indices.push(nextI * stride + j);
  33299. }
  33300. }
  33301. // Sides
  33302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33303. // Result
  33304. var vertexData = new VertexData();
  33305. vertexData.indices = indices;
  33306. vertexData.positions = positions;
  33307. vertexData.normals = normals;
  33308. vertexData.uvs = uvs;
  33309. return vertexData;
  33310. };
  33311. /**
  33312. * Creates the VertexData of the LineSystem.
  33313. */
  33314. VertexData.CreateLineSystem = function (options) {
  33315. var indices = [];
  33316. var positions = [];
  33317. var lines = options.lines;
  33318. var colors = options.colors;
  33319. var vertexColors = [];
  33320. var idx = 0;
  33321. for (var l = 0; l < lines.length; l++) {
  33322. var points = lines[l];
  33323. for (var index = 0; index < points.length; index++) {
  33324. positions.push(points[index].x, points[index].y, points[index].z);
  33325. if (colors) {
  33326. var color = colors[l];
  33327. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33328. }
  33329. if (index > 0) {
  33330. indices.push(idx - 1);
  33331. indices.push(idx);
  33332. }
  33333. idx++;
  33334. }
  33335. }
  33336. var vertexData = new VertexData();
  33337. vertexData.indices = indices;
  33338. vertexData.positions = positions;
  33339. if (colors) {
  33340. vertexData.colors = vertexColors;
  33341. }
  33342. return vertexData;
  33343. };
  33344. /**
  33345. * Create the VertexData of the DashedLines.
  33346. */
  33347. VertexData.CreateDashedLines = function (options) {
  33348. var dashSize = options.dashSize || 3;
  33349. var gapSize = options.gapSize || 1;
  33350. var dashNb = options.dashNb || 200;
  33351. var points = options.points;
  33352. var positions = new Array();
  33353. var indices = new Array();
  33354. var curvect = BABYLON.Vector3.Zero();
  33355. var lg = 0;
  33356. var nb = 0;
  33357. var shft = 0;
  33358. var dashshft = 0;
  33359. var curshft = 0;
  33360. var idx = 0;
  33361. var i = 0;
  33362. for (i = 0; i < points.length - 1; i++) {
  33363. points[i + 1].subtractToRef(points[i], curvect);
  33364. lg += curvect.length();
  33365. }
  33366. shft = lg / dashNb;
  33367. dashshft = dashSize * shft / (dashSize + gapSize);
  33368. for (i = 0; i < points.length - 1; i++) {
  33369. points[i + 1].subtractToRef(points[i], curvect);
  33370. nb = Math.floor(curvect.length() / shft);
  33371. curvect.normalize();
  33372. for (var j = 0; j < nb; j++) {
  33373. curshft = shft * j;
  33374. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33375. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33376. indices.push(idx, idx + 1);
  33377. idx += 2;
  33378. }
  33379. }
  33380. // Result
  33381. var vertexData = new VertexData();
  33382. vertexData.positions = positions;
  33383. vertexData.indices = indices;
  33384. return vertexData;
  33385. };
  33386. /**
  33387. * Creates the VertexData of the Ground.
  33388. */
  33389. VertexData.CreateGround = function (options) {
  33390. var indices = [];
  33391. var positions = [];
  33392. var normals = [];
  33393. var uvs = [];
  33394. var row, col;
  33395. var width = options.width || 1;
  33396. var height = options.height || 1;
  33397. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33398. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33399. for (row = 0; row <= subdivisionsY; row++) {
  33400. for (col = 0; col <= subdivisionsX; col++) {
  33401. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33402. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33403. positions.push(position.x, position.y, position.z);
  33404. normals.push(normal.x, normal.y, normal.z);
  33405. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33406. }
  33407. }
  33408. for (row = 0; row < subdivisionsY; row++) {
  33409. for (col = 0; col < subdivisionsX; col++) {
  33410. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33411. indices.push(col + 1 + row * (subdivisionsX + 1));
  33412. indices.push(col + row * (subdivisionsX + 1));
  33413. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33414. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33415. indices.push(col + row * (subdivisionsX + 1));
  33416. }
  33417. }
  33418. // Result
  33419. var vertexData = new VertexData();
  33420. vertexData.indices = indices;
  33421. vertexData.positions = positions;
  33422. vertexData.normals = normals;
  33423. vertexData.uvs = uvs;
  33424. return vertexData;
  33425. };
  33426. /**
  33427. * Creates the VertexData of the TiledGround.
  33428. */
  33429. VertexData.CreateTiledGround = function (options) {
  33430. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33431. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33432. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33433. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33434. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33435. var precision = options.precision || { w: 1, h: 1 };
  33436. var indices = new Array();
  33437. var positions = new Array();
  33438. var normals = new Array();
  33439. var uvs = new Array();
  33440. var row, col, tileRow, tileCol;
  33441. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33442. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33443. precision.w = (precision.w < 1) ? 1 : precision.w;
  33444. precision.h = (precision.h < 1) ? 1 : precision.h;
  33445. var tileSize = {
  33446. 'w': (xmax - xmin) / subdivisions.w,
  33447. 'h': (zmax - zmin) / subdivisions.h
  33448. };
  33449. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33450. // Indices
  33451. var base = positions.length / 3;
  33452. var rowLength = precision.w + 1;
  33453. for (row = 0; row < precision.h; row++) {
  33454. for (col = 0; col < precision.w; col++) {
  33455. var square = [
  33456. base + col + row * rowLength,
  33457. base + (col + 1) + row * rowLength,
  33458. base + (col + 1) + (row + 1) * rowLength,
  33459. base + col + (row + 1) * rowLength
  33460. ];
  33461. indices.push(square[1]);
  33462. indices.push(square[2]);
  33463. indices.push(square[3]);
  33464. indices.push(square[0]);
  33465. indices.push(square[1]);
  33466. indices.push(square[3]);
  33467. }
  33468. }
  33469. // Position, normals and uvs
  33470. var position = BABYLON.Vector3.Zero();
  33471. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33472. for (row = 0; row <= precision.h; row++) {
  33473. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33474. for (col = 0; col <= precision.w; col++) {
  33475. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33476. position.y = 0;
  33477. positions.push(position.x, position.y, position.z);
  33478. normals.push(normal.x, normal.y, normal.z);
  33479. uvs.push(col / precision.w, row / precision.h);
  33480. }
  33481. }
  33482. }
  33483. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33484. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33485. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33486. }
  33487. }
  33488. // Result
  33489. var vertexData = new VertexData();
  33490. vertexData.indices = indices;
  33491. vertexData.positions = positions;
  33492. vertexData.normals = normals;
  33493. vertexData.uvs = uvs;
  33494. return vertexData;
  33495. };
  33496. /**
  33497. * Creates the VertexData of the Ground designed from a heightmap.
  33498. */
  33499. VertexData.CreateGroundFromHeightMap = function (options) {
  33500. var indices = [];
  33501. var positions = [];
  33502. var normals = [];
  33503. var uvs = [];
  33504. var row, col;
  33505. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33506. // Vertices
  33507. for (row = 0; row <= options.subdivisions; row++) {
  33508. for (col = 0; col <= options.subdivisions; col++) {
  33509. 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));
  33510. // Compute height
  33511. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33512. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33513. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33514. var r = options.buffer[pos] / 255.0;
  33515. var g = options.buffer[pos + 1] / 255.0;
  33516. var b = options.buffer[pos + 2] / 255.0;
  33517. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33518. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33519. // Add vertex
  33520. positions.push(position.x, position.y, position.z);
  33521. normals.push(0, 0, 0);
  33522. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33523. }
  33524. }
  33525. // Indices
  33526. for (row = 0; row < options.subdivisions; row++) {
  33527. for (col = 0; col < options.subdivisions; col++) {
  33528. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33529. indices.push(col + 1 + row * (options.subdivisions + 1));
  33530. indices.push(col + row * (options.subdivisions + 1));
  33531. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33532. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33533. indices.push(col + row * (options.subdivisions + 1));
  33534. }
  33535. }
  33536. // Normals
  33537. VertexData.ComputeNormals(positions, indices, normals);
  33538. // Result
  33539. var vertexData = new VertexData();
  33540. vertexData.indices = indices;
  33541. vertexData.positions = positions;
  33542. vertexData.normals = normals;
  33543. vertexData.uvs = uvs;
  33544. return vertexData;
  33545. };
  33546. /**
  33547. * Creates the VertexData of the Plane.
  33548. */
  33549. VertexData.CreatePlane = function (options) {
  33550. var indices = [];
  33551. var positions = [];
  33552. var normals = [];
  33553. var uvs = [];
  33554. var width = options.width || options.size || 1;
  33555. var height = options.height || options.size || 1;
  33556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33557. // Vertices
  33558. var halfWidth = width / 2.0;
  33559. var halfHeight = height / 2.0;
  33560. positions.push(-halfWidth, -halfHeight, 0);
  33561. normals.push(0, 0, -1.0);
  33562. uvs.push(0.0, 0.0);
  33563. positions.push(halfWidth, -halfHeight, 0);
  33564. normals.push(0, 0, -1.0);
  33565. uvs.push(1.0, 0.0);
  33566. positions.push(halfWidth, halfHeight, 0);
  33567. normals.push(0, 0, -1.0);
  33568. uvs.push(1.0, 1.0);
  33569. positions.push(-halfWidth, halfHeight, 0);
  33570. normals.push(0, 0, -1.0);
  33571. uvs.push(0.0, 1.0);
  33572. // Indices
  33573. indices.push(0);
  33574. indices.push(1);
  33575. indices.push(2);
  33576. indices.push(0);
  33577. indices.push(2);
  33578. indices.push(3);
  33579. // Sides
  33580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33581. // Result
  33582. var vertexData = new VertexData();
  33583. vertexData.indices = indices;
  33584. vertexData.positions = positions;
  33585. vertexData.normals = normals;
  33586. vertexData.uvs = uvs;
  33587. return vertexData;
  33588. };
  33589. /**
  33590. * Creates the VertexData of the Disc or regular Polygon.
  33591. */
  33592. VertexData.CreateDisc = function (options) {
  33593. var positions = new Array();
  33594. var indices = new Array();
  33595. var normals = new Array();
  33596. var uvs = new Array();
  33597. var radius = options.radius || 0.5;
  33598. var tessellation = options.tessellation || 64;
  33599. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33600. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33601. // positions and uvs
  33602. positions.push(0, 0, 0); // disc center first
  33603. uvs.push(0.5, 0.5);
  33604. var theta = Math.PI * 2 * arc;
  33605. var step = theta / tessellation;
  33606. for (var a = 0; a < theta; a += step) {
  33607. var x = Math.cos(a);
  33608. var y = Math.sin(a);
  33609. var u = (x + 1) / 2;
  33610. var v = (1 - y) / 2;
  33611. positions.push(radius * x, radius * y, 0);
  33612. uvs.push(u, v);
  33613. }
  33614. if (arc === 1) {
  33615. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33616. uvs.push(uvs[2], uvs[3]);
  33617. }
  33618. //indices
  33619. var vertexNb = positions.length / 3;
  33620. for (var i = 1; i < vertexNb - 1; i++) {
  33621. indices.push(i + 1, 0, i);
  33622. }
  33623. // result
  33624. VertexData.ComputeNormals(positions, indices, normals);
  33625. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33626. var vertexData = new VertexData();
  33627. vertexData.indices = indices;
  33628. vertexData.positions = positions;
  33629. vertexData.normals = normals;
  33630. vertexData.uvs = uvs;
  33631. return vertexData;
  33632. };
  33633. /**
  33634. * Re-creates the VertexData of the Polygon for sideOrientation.
  33635. */
  33636. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33637. var faceUV = fUV || new Array(3);
  33638. var faceColors = fColors;
  33639. var colors = [];
  33640. // default face colors and UV if undefined
  33641. for (var f = 0; f < 3; f++) {
  33642. if (faceUV[f] === undefined) {
  33643. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33644. }
  33645. if (faceColors && faceColors[f] === undefined) {
  33646. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33647. }
  33648. }
  33649. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33650. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33651. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33652. var indices = polygon.getIndices();
  33653. // set face colours and textures
  33654. var idx = 0;
  33655. var face = 0;
  33656. for (var index = 0; index < normals.length; index += 3) {
  33657. //Edge Face no. 1
  33658. if (Math.abs(normals[index + 1]) < 0.001) {
  33659. face = 1;
  33660. }
  33661. //Top Face no. 0
  33662. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33663. face = 0;
  33664. }
  33665. //Bottom Face no. 2
  33666. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33667. face = 2;
  33668. }
  33669. idx = index / 3;
  33670. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33671. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33672. if (faceColors) {
  33673. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33674. }
  33675. }
  33676. // sides
  33677. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33678. // Result
  33679. var vertexData = new VertexData();
  33680. vertexData.indices = indices;
  33681. vertexData.positions = positions;
  33682. vertexData.normals = normals;
  33683. vertexData.uvs = uvs;
  33684. if (faceColors) {
  33685. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33686. vertexData.colors = totalColors;
  33687. }
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Creates the VertexData of the IcoSphere.
  33692. */
  33693. VertexData.CreateIcoSphere = function (options) {
  33694. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33695. var radius = options.radius || 1;
  33696. var flat = (options.flat === undefined) ? true : options.flat;
  33697. var subdivisions = options.subdivisions || 4;
  33698. var radiusX = options.radiusX || radius;
  33699. var radiusY = options.radiusY || radius;
  33700. var radiusZ = options.radiusZ || radius;
  33701. var t = (1 + Math.sqrt(5)) / 2;
  33702. // 12 vertex x,y,z
  33703. var ico_vertices = [
  33704. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33705. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33706. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33707. ];
  33708. // index of 3 vertex makes a face of icopshere
  33709. var ico_indices = [
  33710. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33711. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33712. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33713. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33714. ];
  33715. // vertex for uv have aliased position, not for UV
  33716. var vertices_unalias_id = [
  33717. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33718. // vertex alias
  33719. 0,
  33720. 2,
  33721. 3,
  33722. 3,
  33723. 3,
  33724. 4,
  33725. 7,
  33726. 8,
  33727. 9,
  33728. 9,
  33729. 10,
  33730. 11 // 23: B + 12
  33731. ];
  33732. // uv as integer step (not pixels !)
  33733. var ico_vertexuv = [
  33734. 5, 1, 3, 1, 6, 4, 0, 0,
  33735. 5, 3, 4, 2, 2, 2, 4, 0,
  33736. 2, 0, 1, 1, 6, 0, 6, 2,
  33737. // vertex alias (for same vertex on different faces)
  33738. 0, 4,
  33739. 3, 3,
  33740. 4, 4,
  33741. 3, 1,
  33742. 4, 2,
  33743. 4, 4,
  33744. 0, 2,
  33745. 1, 1,
  33746. 2, 2,
  33747. 3, 3,
  33748. 1, 3,
  33749. 2, 4 // 23: B + 12
  33750. ];
  33751. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33752. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33753. // First island of uv mapping
  33754. // v = 4h 3+ 2
  33755. // v = 3h 9+ 4
  33756. // v = 2h 9+ 5 B
  33757. // v = 1h 9 1 0
  33758. // v = 0h 3 8 7 A
  33759. // u = 0 1 2 3 4 5 6 *a
  33760. // Second island of uv mapping
  33761. // v = 4h 0+ B+ 4+
  33762. // v = 3h A+ 2+
  33763. // v = 2h 7+ 6 3+
  33764. // v = 1h 8+ 3+
  33765. // v = 0h
  33766. // u = 0 1 2 3 4 5 6 *a
  33767. // Face layout on texture UV mapping
  33768. // ============
  33769. // \ 4 /\ 16 / ======
  33770. // \ / \ / /\ 11 /
  33771. // \/ 7 \/ / \ /
  33772. // ======= / 10 \/
  33773. // /\ 17 /\ =======
  33774. // / \ / \ \ 15 /\
  33775. // / 8 \/ 12 \ \ / \
  33776. // ============ \/ 6 \
  33777. // \ 18 /\ ============
  33778. // \ / \ \ 5 /\ 0 /
  33779. // \/ 13 \ \ / \ /
  33780. // ======= \/ 1 \/
  33781. // =============
  33782. // /\ 19 /\ 2 /\
  33783. // / \ / \ / \
  33784. // / 14 \/ 9 \/ 3 \
  33785. // ===================
  33786. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33787. var ustep = 138 / 1024;
  33788. var vstep = 239 / 1024;
  33789. var uoffset = 60 / 1024;
  33790. var voffset = 26 / 1024;
  33791. // Second island should have margin, not to touch the first island
  33792. // avoid any borderline artefact in pixel rounding
  33793. var island_u_offset = -40 / 1024;
  33794. var island_v_offset = +20 / 1024;
  33795. // face is either island 0 or 1 :
  33796. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33797. var island = [
  33798. 0, 0, 0, 0, 1,
  33799. 0, 0, 1, 1, 0,
  33800. 0, 0, 1, 1, 0,
  33801. 0, 1, 1, 1, 0 // 15 - 19
  33802. ];
  33803. var indices = new Array();
  33804. var positions = new Array();
  33805. var normals = new Array();
  33806. var uvs = new Array();
  33807. var current_indice = 0;
  33808. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33809. var face_vertex_pos = new Array(3);
  33810. var face_vertex_uv = new Array(3);
  33811. var v012;
  33812. for (v012 = 0; v012 < 3; v012++) {
  33813. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33814. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33815. }
  33816. // create all with normals
  33817. for (var face = 0; face < 20; face++) {
  33818. // 3 vertex per face
  33819. for (v012 = 0; v012 < 3; v012++) {
  33820. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33821. var v_id = ico_indices[3 * face + v012];
  33822. // vertex have 3D position (x,y,z)
  33823. 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]);
  33824. // Normalize to get normal, then scale to radius
  33825. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33826. // uv Coordinates from vertex ID
  33827. 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);
  33828. }
  33829. // Subdivide the face (interpolate pos, norm, uv)
  33830. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33831. // - norm is linear interpolation of vertex corner normal
  33832. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33833. // - uv is linear interpolation
  33834. //
  33835. // Topology is as below for sub-divide by 2
  33836. // vertex shown as v0,v1,v2
  33837. // interp index is i1 to progress in range [v0,v1[
  33838. // interp index is i2 to progress in range [v0,v2[
  33839. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33840. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33841. //
  33842. //
  33843. // i2 v2
  33844. // ^ ^
  33845. // / / \
  33846. // / / \
  33847. // / / \
  33848. // / / (0,1) \
  33849. // / #---------\
  33850. // / / \ (0,0)'/ \
  33851. // / / \ / \
  33852. // / / \ / \
  33853. // / / (0,0) \ / (1,0) \
  33854. // / #---------#---------\
  33855. // v0 v1
  33856. //
  33857. // --------------------> i1
  33858. //
  33859. // interp of (i1,i2):
  33860. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33861. // along i1 : lerp(x0,x1, i1/(S-i2))
  33862. //
  33863. // centroid of triangle is needed to get help normal computation
  33864. // (c1,c2) are used for centroid location
  33865. var interp_vertex = function (i1, i2, c1, c2) {
  33866. // vertex is interpolated from
  33867. // - face_vertex_pos[0..2]
  33868. // - face_vertex_uv[0..2]
  33869. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33870. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33871. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33872. pos_interp.normalize();
  33873. var vertex_normal;
  33874. if (flat) {
  33875. // in flat mode, recalculate normal as face centroid normal
  33876. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33877. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33878. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33879. }
  33880. else {
  33881. // in smooth mode, recalculate normal from each single vertex position
  33882. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33883. }
  33884. // Vertex normal need correction due to X,Y,Z radius scaling
  33885. vertex_normal.x /= radiusX;
  33886. vertex_normal.y /= radiusY;
  33887. vertex_normal.z /= radiusZ;
  33888. vertex_normal.normalize();
  33889. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33890. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33891. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33892. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33893. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33894. uvs.push(uv_interp.x, uv_interp.y);
  33895. // push each vertex has member of a face
  33896. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33897. indices.push(current_indice);
  33898. current_indice++;
  33899. };
  33900. for (var i2 = 0; i2 < subdivisions; i2++) {
  33901. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33902. // face : (i1,i2) for /\ :
  33903. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33904. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33905. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33906. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33907. if (i1 + i2 + 1 < subdivisions) {
  33908. // face : (i1,i2)' for \/ :
  33909. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33910. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33911. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33912. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33913. }
  33914. }
  33915. }
  33916. }
  33917. // Sides
  33918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33919. // Result
  33920. var vertexData = new VertexData();
  33921. vertexData.indices = indices;
  33922. vertexData.positions = positions;
  33923. vertexData.normals = normals;
  33924. vertexData.uvs = uvs;
  33925. return vertexData;
  33926. };
  33927. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33928. /**
  33929. * Creates the VertexData of the Polyhedron.
  33930. */
  33931. VertexData.CreatePolyhedron = function (options) {
  33932. // provided polyhedron types :
  33933. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33934. // 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)
  33935. var polyhedra = [];
  33936. 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]] };
  33937. 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]] };
  33938. polyhedra[2] = {
  33939. 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]],
  33940. 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]]
  33941. };
  33942. polyhedra[3] = {
  33943. 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]],
  33944. 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]]
  33945. };
  33946. polyhedra[4] = {
  33947. 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]],
  33948. 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]]
  33949. };
  33950. 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]] };
  33951. 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]] };
  33952. 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]] };
  33953. 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]] };
  33954. 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]] };
  33955. 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]] };
  33956. 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]] };
  33957. 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]] };
  33958. 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]] };
  33959. polyhedra[14] = {
  33960. 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]],
  33961. 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]]
  33962. };
  33963. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33964. var size = options.size;
  33965. var sizeX = options.sizeX || size || 1;
  33966. var sizeY = options.sizeY || size || 1;
  33967. var sizeZ = options.sizeZ || size || 1;
  33968. var data = options.custom || polyhedra[type];
  33969. var nbfaces = data.face.length;
  33970. var faceUV = options.faceUV || new Array(nbfaces);
  33971. var faceColors = options.faceColors;
  33972. var flat = (options.flat === undefined) ? true : options.flat;
  33973. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33974. var positions = new Array();
  33975. var indices = new Array();
  33976. var normals = new Array();
  33977. var uvs = new Array();
  33978. var colors = new Array();
  33979. var index = 0;
  33980. var faceIdx = 0; // face cursor in the array "indexes"
  33981. var indexes = new Array();
  33982. var i = 0;
  33983. var f = 0;
  33984. var u, v, ang, x, y, tmp;
  33985. // default face colors and UV if undefined
  33986. if (flat) {
  33987. for (f = 0; f < nbfaces; f++) {
  33988. if (faceColors && faceColors[f] === undefined) {
  33989. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33990. }
  33991. if (faceUV && faceUV[f] === undefined) {
  33992. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33993. }
  33994. }
  33995. }
  33996. if (!flat) {
  33997. for (i = 0; i < data.vertex.length; i++) {
  33998. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33999. uvs.push(0, 0);
  34000. }
  34001. for (f = 0; f < nbfaces; f++) {
  34002. for (i = 0; i < data.face[f].length - 2; i++) {
  34003. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34004. }
  34005. }
  34006. }
  34007. else {
  34008. for (f = 0; f < nbfaces; f++) {
  34009. var fl = data.face[f].length; // number of vertices of the current face
  34010. ang = 2 * Math.PI / fl;
  34011. x = 0.5 * Math.tan(ang / 2);
  34012. y = 0.5;
  34013. // positions, uvs, colors
  34014. for (i = 0; i < fl; i++) {
  34015. // positions
  34016. 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);
  34017. indexes.push(index);
  34018. index++;
  34019. // uvs
  34020. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34021. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34022. uvs.push(u, v);
  34023. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34024. y = x * Math.sin(ang) + y * Math.cos(ang);
  34025. x = tmp;
  34026. // colors
  34027. if (faceColors) {
  34028. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34029. }
  34030. }
  34031. // indices from indexes
  34032. for (i = 0; i < fl - 2; i++) {
  34033. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34034. }
  34035. faceIdx += fl;
  34036. }
  34037. }
  34038. VertexData.ComputeNormals(positions, indices, normals);
  34039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34040. var vertexData = new VertexData();
  34041. vertexData.positions = positions;
  34042. vertexData.indices = indices;
  34043. vertexData.normals = normals;
  34044. vertexData.uvs = uvs;
  34045. if (faceColors && flat) {
  34046. vertexData.colors = colors;
  34047. }
  34048. return vertexData;
  34049. };
  34050. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34051. /**
  34052. * Creates the VertexData of the Torus Knot.
  34053. */
  34054. VertexData.CreateTorusKnot = function (options) {
  34055. var indices = new Array();
  34056. var positions = new Array();
  34057. var normals = new Array();
  34058. var uvs = new Array();
  34059. var radius = options.radius || 2;
  34060. var tube = options.tube || 0.5;
  34061. var radialSegments = options.radialSegments || 32;
  34062. var tubularSegments = options.tubularSegments || 32;
  34063. var p = options.p || 2;
  34064. var q = options.q || 3;
  34065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34066. // Helper
  34067. var getPos = function (angle) {
  34068. var cu = Math.cos(angle);
  34069. var su = Math.sin(angle);
  34070. var quOverP = q / p * angle;
  34071. var cs = Math.cos(quOverP);
  34072. var tx = radius * (2 + cs) * 0.5 * cu;
  34073. var ty = radius * (2 + cs) * su * 0.5;
  34074. var tz = radius * Math.sin(quOverP) * 0.5;
  34075. return new BABYLON.Vector3(tx, ty, tz);
  34076. };
  34077. // Vertices
  34078. var i;
  34079. var j;
  34080. for (i = 0; i <= radialSegments; i++) {
  34081. var modI = i % radialSegments;
  34082. var u = modI / radialSegments * 2 * p * Math.PI;
  34083. var p1 = getPos(u);
  34084. var p2 = getPos(u + 0.01);
  34085. var tang = p2.subtract(p1);
  34086. var n = p2.add(p1);
  34087. var bitan = BABYLON.Vector3.Cross(tang, n);
  34088. n = BABYLON.Vector3.Cross(bitan, tang);
  34089. bitan.normalize();
  34090. n.normalize();
  34091. for (j = 0; j < tubularSegments; j++) {
  34092. var modJ = j % tubularSegments;
  34093. var v = modJ / tubularSegments * 2 * Math.PI;
  34094. var cx = -tube * Math.cos(v);
  34095. var cy = tube * Math.sin(v);
  34096. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34097. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34098. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34099. uvs.push(i / radialSegments);
  34100. uvs.push(j / tubularSegments);
  34101. }
  34102. }
  34103. for (i = 0; i < radialSegments; i++) {
  34104. for (j = 0; j < tubularSegments; j++) {
  34105. var jNext = (j + 1) % tubularSegments;
  34106. var a = i * tubularSegments + j;
  34107. var b = (i + 1) * tubularSegments + j;
  34108. var c = (i + 1) * tubularSegments + jNext;
  34109. var d = i * tubularSegments + jNext;
  34110. indices.push(d);
  34111. indices.push(b);
  34112. indices.push(a);
  34113. indices.push(d);
  34114. indices.push(c);
  34115. indices.push(b);
  34116. }
  34117. }
  34118. // Normals
  34119. VertexData.ComputeNormals(positions, indices, normals);
  34120. // Sides
  34121. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34122. // Result
  34123. var vertexData = new VertexData();
  34124. vertexData.indices = indices;
  34125. vertexData.positions = positions;
  34126. vertexData.normals = normals;
  34127. vertexData.uvs = uvs;
  34128. return vertexData;
  34129. };
  34130. // Tools
  34131. /**
  34132. * @param {any} - positions (number[] or Float32Array)
  34133. * @param {any} - indices (number[] or Uint16Array)
  34134. * @param {any} - normals (number[] or Float32Array)
  34135. * options (optional) :
  34136. * facetPositions : optional array of facet positions (vector3)
  34137. * facetNormals : optional array of facet normals (vector3)
  34138. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34139. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34140. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34141. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34142. * bInfo : optional bounding info, required for facetPartitioning computation
  34143. * useRightHandedSystem: optional boolean to for right handed system computation
  34144. * depthSort : optional boolean to enable the facet depth sort computation
  34145. * distanceTo : optional Vector3 to compute the facet depth from this location
  34146. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34147. */
  34148. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34149. // temporary scalar variables
  34150. var index = 0; // facet index
  34151. var p1p2x = 0.0; // p1p2 vector x coordinate
  34152. var p1p2y = 0.0; // p1p2 vector y coordinate
  34153. var p1p2z = 0.0; // p1p2 vector z coordinate
  34154. var p3p2x = 0.0; // p3p2 vector x coordinate
  34155. var p3p2y = 0.0; // p3p2 vector y coordinate
  34156. var p3p2z = 0.0; // p3p2 vector z coordinate
  34157. var faceNormalx = 0.0; // facet normal x coordinate
  34158. var faceNormaly = 0.0; // facet normal y coordinate
  34159. var faceNormalz = 0.0; // facet normal z coordinate
  34160. var length = 0.0; // facet normal length before normalization
  34161. var v1x = 0; // vector1 x index in the positions array
  34162. var v1y = 0; // vector1 y index in the positions array
  34163. var v1z = 0; // vector1 z index in the positions array
  34164. var v2x = 0; // vector2 x index in the positions array
  34165. var v2y = 0; // vector2 y index in the positions array
  34166. var v2z = 0; // vector2 z index in the positions array
  34167. var v3x = 0; // vector3 x index in the positions array
  34168. var v3y = 0; // vector3 y index in the positions array
  34169. var v3z = 0; // vector3 z index in the positions array
  34170. var computeFacetNormals = false;
  34171. var computeFacetPositions = false;
  34172. var computeFacetPartitioning = false;
  34173. var computeDepthSort = false;
  34174. var faceNormalSign = 1;
  34175. var ratio = 0;
  34176. var distanceTo = null;
  34177. if (options) {
  34178. computeFacetNormals = (options.facetNormals) ? true : false;
  34179. computeFacetPositions = (options.facetPositions) ? true : false;
  34180. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34181. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34182. ratio = options.ratio || 0;
  34183. computeDepthSort = (options.depthSort) ? true : false;
  34184. distanceTo = (options.distanceTo);
  34185. if (computeDepthSort) {
  34186. if (distanceTo === undefined) {
  34187. distanceTo = BABYLON.Vector3.Zero();
  34188. }
  34189. var depthSortedFacets = options.depthSortedFacets;
  34190. }
  34191. }
  34192. // facetPartitioning reinit if needed
  34193. var xSubRatio = 0;
  34194. var ySubRatio = 0;
  34195. var zSubRatio = 0;
  34196. var subSq = 0;
  34197. if (computeFacetPartitioning && options && options.bbSize) {
  34198. var ox = 0; // X partitioning index for facet position
  34199. var oy = 0; // Y partinioning index for facet position
  34200. var oz = 0; // Z partinioning index for facet position
  34201. var b1x = 0; // X partitioning index for facet v1 vertex
  34202. var b1y = 0; // Y partitioning index for facet v1 vertex
  34203. var b1z = 0; // z partitioning index for facet v1 vertex
  34204. var b2x = 0; // X partitioning index for facet v2 vertex
  34205. var b2y = 0; // Y partitioning index for facet v2 vertex
  34206. var b2z = 0; // Z partitioning index for facet v2 vertex
  34207. var b3x = 0; // X partitioning index for facet v3 vertex
  34208. var b3y = 0; // Y partitioning index for facet v3 vertex
  34209. var b3z = 0; // Z partitioning index for facet v3 vertex
  34210. var block_idx_o = 0; // facet barycenter block index
  34211. var block_idx_v1 = 0; // v1 vertex block index
  34212. var block_idx_v2 = 0; // v2 vertex block index
  34213. var block_idx_v3 = 0; // v3 vertex block index
  34214. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34215. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34216. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34217. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34218. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34219. subSq = options.subDiv.max * options.subDiv.max;
  34220. options.facetPartitioning.length = 0;
  34221. }
  34222. // reset the normals
  34223. for (index = 0; index < positions.length; index++) {
  34224. normals[index] = 0.0;
  34225. }
  34226. // Loop : 1 indice triplet = 1 facet
  34227. var nbFaces = (indices.length / 3) | 0;
  34228. for (index = 0; index < nbFaces; index++) {
  34229. // get the indexes of the coordinates of each vertex of the facet
  34230. v1x = indices[index * 3] * 3;
  34231. v1y = v1x + 1;
  34232. v1z = v1x + 2;
  34233. v2x = indices[index * 3 + 1] * 3;
  34234. v2y = v2x + 1;
  34235. v2z = v2x + 2;
  34236. v3x = indices[index * 3 + 2] * 3;
  34237. v3y = v3x + 1;
  34238. v3z = v3x + 2;
  34239. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34240. p1p2y = positions[v1y] - positions[v2y];
  34241. p1p2z = positions[v1z] - positions[v2z];
  34242. p3p2x = positions[v3x] - positions[v2x];
  34243. p3p2y = positions[v3y] - positions[v2y];
  34244. p3p2z = positions[v3z] - positions[v2z];
  34245. // compute the face normal with the cross product
  34246. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34247. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34248. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34249. // normalize this normal and store it in the array facetData
  34250. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34251. length = (length === 0) ? 1.0 : length;
  34252. faceNormalx /= length;
  34253. faceNormaly /= length;
  34254. faceNormalz /= length;
  34255. if (computeFacetNormals && options) {
  34256. options.facetNormals[index].x = faceNormalx;
  34257. options.facetNormals[index].y = faceNormaly;
  34258. options.facetNormals[index].z = faceNormalz;
  34259. }
  34260. if (computeFacetPositions && options) {
  34261. // compute and the facet barycenter coordinates in the array facetPositions
  34262. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34263. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34264. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34265. }
  34266. if (computeFacetPartitioning && options) {
  34267. // store the facet indexes in arrays in the main facetPartitioning array :
  34268. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34269. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34270. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34271. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34272. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34273. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34274. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34275. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34276. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34277. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34278. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34279. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34280. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34281. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34282. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34283. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34284. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34285. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34286. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34287. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34288. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34289. // push each facet index in each block containing the vertex
  34290. options.facetPartitioning[block_idx_v1].push(index);
  34291. if (block_idx_v2 != block_idx_v1) {
  34292. options.facetPartitioning[block_idx_v2].push(index);
  34293. }
  34294. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34295. options.facetPartitioning[block_idx_v3].push(index);
  34296. }
  34297. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34298. options.facetPartitioning[block_idx_o].push(index);
  34299. }
  34300. }
  34301. if (computeDepthSort && options && options.facetPositions) {
  34302. var dsf = depthSortedFacets[index];
  34303. dsf.ind = index * 3;
  34304. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34305. }
  34306. // compute the normals anyway
  34307. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34308. normals[v1y] += faceNormaly;
  34309. normals[v1z] += faceNormalz;
  34310. normals[v2x] += faceNormalx;
  34311. normals[v2y] += faceNormaly;
  34312. normals[v2z] += faceNormalz;
  34313. normals[v3x] += faceNormalx;
  34314. normals[v3y] += faceNormaly;
  34315. normals[v3z] += faceNormalz;
  34316. }
  34317. // last normalization of each normal
  34318. for (index = 0; index < normals.length / 3; index++) {
  34319. faceNormalx = normals[index * 3];
  34320. faceNormaly = normals[index * 3 + 1];
  34321. faceNormalz = normals[index * 3 + 2];
  34322. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34323. length = (length === 0) ? 1.0 : length;
  34324. faceNormalx /= length;
  34325. faceNormaly /= length;
  34326. faceNormalz /= length;
  34327. normals[index * 3] = faceNormalx;
  34328. normals[index * 3 + 1] = faceNormaly;
  34329. normals[index * 3 + 2] = faceNormalz;
  34330. }
  34331. };
  34332. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34333. var li = indices.length;
  34334. var ln = normals.length;
  34335. var i;
  34336. var n;
  34337. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34338. switch (sideOrientation) {
  34339. case BABYLON.Mesh.FRONTSIDE:
  34340. // nothing changed
  34341. break;
  34342. case BABYLON.Mesh.BACKSIDE:
  34343. var tmp;
  34344. // indices
  34345. for (i = 0; i < li; i += 3) {
  34346. tmp = indices[i];
  34347. indices[i] = indices[i + 2];
  34348. indices[i + 2] = tmp;
  34349. }
  34350. // normals
  34351. for (n = 0; n < ln; n++) {
  34352. normals[n] = -normals[n];
  34353. }
  34354. break;
  34355. case BABYLON.Mesh.DOUBLESIDE:
  34356. // positions
  34357. var lp = positions.length;
  34358. var l = lp / 3;
  34359. for (var p = 0; p < lp; p++) {
  34360. positions[lp + p] = positions[p];
  34361. }
  34362. // indices
  34363. for (i = 0; i < li; i += 3) {
  34364. indices[i + li] = indices[i + 2] + l;
  34365. indices[i + 1 + li] = indices[i + 1] + l;
  34366. indices[i + 2 + li] = indices[i] + l;
  34367. }
  34368. // normals
  34369. for (n = 0; n < ln; n++) {
  34370. normals[ln + n] = -normals[n];
  34371. }
  34372. // uvs
  34373. var lu = uvs.length;
  34374. var u = 0;
  34375. for (u = 0; u < lu; u++) {
  34376. uvs[u + lu] = uvs[u];
  34377. }
  34378. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34379. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34380. u = 0;
  34381. for (i = 0; i < lu / 2; i++) {
  34382. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34383. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34384. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34385. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34386. u += 2;
  34387. }
  34388. break;
  34389. }
  34390. };
  34391. /**
  34392. * Creates a new VertexData from the imported parameters.
  34393. */
  34394. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34395. var vertexData = new VertexData();
  34396. // positions
  34397. var positions = parsedVertexData.positions;
  34398. if (positions) {
  34399. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34400. }
  34401. // normals
  34402. var normals = parsedVertexData.normals;
  34403. if (normals) {
  34404. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34405. }
  34406. // tangents
  34407. var tangents = parsedVertexData.tangents;
  34408. if (tangents) {
  34409. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34410. }
  34411. // uvs
  34412. var uvs = parsedVertexData.uvs;
  34413. if (uvs) {
  34414. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34415. }
  34416. // uv2s
  34417. var uv2s = parsedVertexData.uv2s;
  34418. if (uv2s) {
  34419. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34420. }
  34421. // uv3s
  34422. var uv3s = parsedVertexData.uv3s;
  34423. if (uv3s) {
  34424. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34425. }
  34426. // uv4s
  34427. var uv4s = parsedVertexData.uv4s;
  34428. if (uv4s) {
  34429. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34430. }
  34431. // uv5s
  34432. var uv5s = parsedVertexData.uv5s;
  34433. if (uv5s) {
  34434. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34435. }
  34436. // uv6s
  34437. var uv6s = parsedVertexData.uv6s;
  34438. if (uv6s) {
  34439. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34440. }
  34441. // colors
  34442. var colors = parsedVertexData.colors;
  34443. if (colors) {
  34444. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34445. }
  34446. // matricesIndices
  34447. var matricesIndices = parsedVertexData.matricesIndices;
  34448. if (matricesIndices) {
  34449. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34450. }
  34451. // matricesWeights
  34452. var matricesWeights = parsedVertexData.matricesWeights;
  34453. if (matricesWeights) {
  34454. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34455. }
  34456. // indices
  34457. var indices = parsedVertexData.indices;
  34458. if (indices) {
  34459. vertexData.indices = indices;
  34460. }
  34461. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34462. };
  34463. return VertexData;
  34464. }());
  34465. BABYLON.VertexData = VertexData;
  34466. })(BABYLON || (BABYLON = {}));
  34467. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34468. var BABYLON;
  34469. (function (BABYLON) {
  34470. /**
  34471. * Class used to store geometry data (vertex buffers + index buffer)
  34472. */
  34473. var Geometry = /** @class */ (function () {
  34474. /**
  34475. * Creates a new geometry
  34476. * @param id defines the unique ID
  34477. * @param scene defines the hosting scene
  34478. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34479. * @param updatable defines if geometry must be updatable (false by default)
  34480. * @param mesh defines the mesh that will be associated with the geometry
  34481. */
  34482. function Geometry(id, scene, vertexData, updatable, mesh) {
  34483. if (updatable === void 0) { updatable = false; }
  34484. if (mesh === void 0) { mesh = null; }
  34485. /**
  34486. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34487. */
  34488. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34489. this._totalVertices = 0;
  34490. this._isDisposed = false;
  34491. this._indexBufferIsUpdatable = false;
  34492. this.id = id;
  34493. this._engine = scene.getEngine();
  34494. this._meshes = [];
  34495. this._scene = scene;
  34496. //Init vertex buffer cache
  34497. this._vertexBuffers = {};
  34498. this._indices = [];
  34499. this._updatable = updatable;
  34500. // vertexData
  34501. if (vertexData) {
  34502. this.setAllVerticesData(vertexData, updatable);
  34503. }
  34504. else {
  34505. this._totalVertices = 0;
  34506. this._indices = [];
  34507. }
  34508. if (this._engine.getCaps().vertexArrayObject) {
  34509. this._vertexArrayObjects = {};
  34510. }
  34511. // applyToMesh
  34512. if (mesh) {
  34513. if (mesh.getClassName() === "LinesMesh") {
  34514. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34515. this.updateExtend();
  34516. }
  34517. this.applyToMesh(mesh);
  34518. mesh.computeWorldMatrix(true);
  34519. }
  34520. }
  34521. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34522. /**
  34523. * 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
  34524. */
  34525. get: function () {
  34526. return this._boundingBias;
  34527. },
  34528. /**
  34529. * 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
  34530. */
  34531. set: function (value) {
  34532. if (this._boundingBias && this._boundingBias.equals(value)) {
  34533. return;
  34534. }
  34535. this._boundingBias = value.clone();
  34536. this.updateBoundingInfo(true, null);
  34537. },
  34538. enumerable: true,
  34539. configurable: true
  34540. });
  34541. /**
  34542. * Static function used to attach a new empty geometry to a mesh
  34543. * @param mesh defines the mesh to attach the geometry to
  34544. * @returns the new {BABYLON.Geometry}
  34545. */
  34546. Geometry.CreateGeometryForMesh = function (mesh) {
  34547. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34548. geometry.applyToMesh(mesh);
  34549. return geometry;
  34550. };
  34551. Object.defineProperty(Geometry.prototype, "extend", {
  34552. /**
  34553. * Gets the current extend of the geometry
  34554. */
  34555. get: function () {
  34556. return this._extend;
  34557. },
  34558. enumerable: true,
  34559. configurable: true
  34560. });
  34561. /**
  34562. * Gets the hosting scene
  34563. * @returns the hosting {BABYLON.Scene}
  34564. */
  34565. Geometry.prototype.getScene = function () {
  34566. return this._scene;
  34567. };
  34568. /**
  34569. * Gets the hosting engine
  34570. * @returns the hosting {BABYLON.Engine}
  34571. */
  34572. Geometry.prototype.getEngine = function () {
  34573. return this._engine;
  34574. };
  34575. /**
  34576. * Defines if the geometry is ready to use
  34577. * @returns true if the geometry is ready to be used
  34578. */
  34579. Geometry.prototype.isReady = function () {
  34580. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34581. };
  34582. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34583. /**
  34584. * Gets a value indicating that the geometry should not be serialized
  34585. */
  34586. get: function () {
  34587. for (var index = 0; index < this._meshes.length; index++) {
  34588. if (!this._meshes[index].doNotSerialize) {
  34589. return false;
  34590. }
  34591. }
  34592. return true;
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. /** @ignore */
  34598. Geometry.prototype._rebuild = function () {
  34599. if (this._vertexArrayObjects) {
  34600. this._vertexArrayObjects = {};
  34601. }
  34602. // Index buffer
  34603. if (this._meshes.length !== 0 && this._indices) {
  34604. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34605. }
  34606. // Vertex buffers
  34607. for (var key in this._vertexBuffers) {
  34608. var vertexBuffer = this._vertexBuffers[key];
  34609. vertexBuffer._rebuild();
  34610. }
  34611. };
  34612. /**
  34613. * Affects all gemetry data in one call
  34614. * @param vertexData defines the geometry data
  34615. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34616. */
  34617. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34618. vertexData.applyToGeometry(this, updatable);
  34619. this.notifyUpdate();
  34620. };
  34621. /**
  34622. * Set specific vertex data
  34623. * @param kind defines the data kind (Position, normal, etc...)
  34624. * @param data defines the vertex data to use
  34625. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34626. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34627. */
  34628. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34629. if (updatable === void 0) { updatable = false; }
  34630. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34631. this.setVerticesBuffer(buffer);
  34632. };
  34633. /**
  34634. * Removes a specific vertex data
  34635. * @param kind defines the data kind (Position, normal, etc...)
  34636. */
  34637. Geometry.prototype.removeVerticesData = function (kind) {
  34638. if (this._vertexBuffers[kind]) {
  34639. this._vertexBuffers[kind].dispose();
  34640. delete this._vertexBuffers[kind];
  34641. }
  34642. };
  34643. /**
  34644. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34645. * @param buffer defines the vertex buffer to use
  34646. */
  34647. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34648. var kind = buffer.getKind();
  34649. if (this._vertexBuffers[kind]) {
  34650. this._vertexBuffers[kind].dispose();
  34651. }
  34652. this._vertexBuffers[kind] = buffer;
  34653. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34654. var data = buffer.getData();
  34655. var stride = buffer.getStrideSize();
  34656. this._totalVertices = data.length / stride;
  34657. this.updateExtend(data, stride);
  34658. this._resetPointsArrayCache();
  34659. var meshes = this._meshes;
  34660. var numOfMeshes = meshes.length;
  34661. for (var index = 0; index < numOfMeshes; index++) {
  34662. var mesh = meshes[index];
  34663. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34664. mesh._createGlobalSubMesh(false);
  34665. mesh.computeWorldMatrix(true);
  34666. }
  34667. }
  34668. this.notifyUpdate(kind);
  34669. if (this._vertexArrayObjects) {
  34670. this._disposeVertexArrayObjects();
  34671. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34672. }
  34673. };
  34674. /**
  34675. * Update a specific vertex buffer
  34676. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34677. * It will do nothing if the buffer is not updatable
  34678. * @param kind defines the data kind (Position, normal, etc...)
  34679. * @param data defines the data to use
  34680. * @param offset defines the offset in the target buffer where to store the data
  34681. */
  34682. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34683. var vertexBuffer = this.getVertexBuffer(kind);
  34684. if (!vertexBuffer) {
  34685. return;
  34686. }
  34687. vertexBuffer.updateDirectly(data, offset);
  34688. this.notifyUpdate(kind);
  34689. };
  34690. /**
  34691. * Update a specific vertex buffer
  34692. * This function will create a new buffer if the current one is not updatable
  34693. * @param kind defines the data kind (Position, normal, etc...)
  34694. * @param data defines the data to use
  34695. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34696. */
  34697. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34698. if (updateExtends === void 0) { updateExtends = false; }
  34699. var vertexBuffer = this.getVertexBuffer(kind);
  34700. if (!vertexBuffer) {
  34701. return;
  34702. }
  34703. vertexBuffer.update(data);
  34704. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34705. var stride = vertexBuffer.getStrideSize();
  34706. this._totalVertices = data.length / stride;
  34707. this.updateBoundingInfo(updateExtends, data);
  34708. }
  34709. this.notifyUpdate(kind);
  34710. };
  34711. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34712. if (updateExtends) {
  34713. this.updateExtend(data);
  34714. }
  34715. var meshes = this._meshes;
  34716. var numOfMeshes = meshes.length;
  34717. this._resetPointsArrayCache();
  34718. for (var index = 0; index < numOfMeshes; index++) {
  34719. var mesh = meshes[index];
  34720. if (updateExtends) {
  34721. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34722. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34723. var subMesh = mesh.subMeshes[subIndex];
  34724. subMesh.refreshBoundingInfo();
  34725. }
  34726. }
  34727. }
  34728. };
  34729. /** @ignore */
  34730. Geometry.prototype._bind = function (effect, indexToBind) {
  34731. if (!effect) {
  34732. return;
  34733. }
  34734. if (indexToBind === undefined) {
  34735. indexToBind = this._indexBuffer;
  34736. }
  34737. var vbs = this.getVertexBuffers();
  34738. if (!vbs) {
  34739. return;
  34740. }
  34741. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34742. this._engine.bindBuffers(vbs, indexToBind, effect);
  34743. return;
  34744. }
  34745. // Using VAO
  34746. if (!this._vertexArrayObjects[effect.key]) {
  34747. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34748. }
  34749. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34750. };
  34751. /**
  34752. * Gets total number of vertices
  34753. * @returns the total number of vertices
  34754. */
  34755. Geometry.prototype.getTotalVertices = function () {
  34756. if (!this.isReady()) {
  34757. return 0;
  34758. }
  34759. return this._totalVertices;
  34760. };
  34761. /**
  34762. * Gets a specific vertex data attached to this geometry
  34763. * @param kind defines the data kind (Position, normal, etc...)
  34764. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34765. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34766. * @returns a float array containing vertex data
  34767. */
  34768. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34769. var vertexBuffer = this.getVertexBuffer(kind);
  34770. if (!vertexBuffer) {
  34771. return null;
  34772. }
  34773. var orig = vertexBuffer.getData();
  34774. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34775. return orig;
  34776. }
  34777. else {
  34778. var len = orig.length;
  34779. var copy = [];
  34780. for (var i = 0; i < len; i++) {
  34781. copy.push(orig[i]);
  34782. }
  34783. return copy;
  34784. }
  34785. };
  34786. /**
  34787. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34788. * @param kind defines the data kind (Position, normal, etc...)
  34789. * @returns true if the vertex buffer with the specified kind is updatable
  34790. */
  34791. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34792. var vb = this._vertexBuffers[kind];
  34793. if (!vb) {
  34794. return false;
  34795. }
  34796. return vb.isUpdatable();
  34797. };
  34798. /**
  34799. * Gets a specific vertex buffer
  34800. * @param kind defines the data kind (Position, normal, etc...)
  34801. * @returns a {BABYLON.VertexBuffer}
  34802. */
  34803. Geometry.prototype.getVertexBuffer = function (kind) {
  34804. if (!this.isReady()) {
  34805. return null;
  34806. }
  34807. return this._vertexBuffers[kind];
  34808. };
  34809. /**
  34810. * Returns all vertex buffers
  34811. * @return an object holding all vertex buffers indexed by kind
  34812. */
  34813. Geometry.prototype.getVertexBuffers = function () {
  34814. if (!this.isReady()) {
  34815. return null;
  34816. }
  34817. return this._vertexBuffers;
  34818. };
  34819. /**
  34820. * Gets a boolean indicating if specific vertex buffer is present
  34821. * @param kind defines the data kind (Position, normal, etc...)
  34822. * @returns true if data is present
  34823. */
  34824. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34825. if (!this._vertexBuffers) {
  34826. if (this._delayInfo) {
  34827. return this._delayInfo.indexOf(kind) !== -1;
  34828. }
  34829. return false;
  34830. }
  34831. return this._vertexBuffers[kind] !== undefined;
  34832. };
  34833. /**
  34834. * Gets a list of all attached data kinds (Position, normal, etc...)
  34835. * @returns a list of string containing all kinds
  34836. */
  34837. Geometry.prototype.getVerticesDataKinds = function () {
  34838. var result = [];
  34839. var kind;
  34840. if (!this._vertexBuffers && this._delayInfo) {
  34841. for (kind in this._delayInfo) {
  34842. result.push(kind);
  34843. }
  34844. }
  34845. else {
  34846. for (kind in this._vertexBuffers) {
  34847. result.push(kind);
  34848. }
  34849. }
  34850. return result;
  34851. };
  34852. /**
  34853. * Update index buffer
  34854. * @param indices defines the indices to store in the index buffer
  34855. * @param offset defines the offset in the target buffer where to store the data
  34856. */
  34857. Geometry.prototype.updateIndices = function (indices, offset) {
  34858. if (!this._indexBuffer) {
  34859. return;
  34860. }
  34861. if (!this._indexBufferIsUpdatable) {
  34862. this.setIndices(indices, null, true);
  34863. }
  34864. else {
  34865. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34866. }
  34867. };
  34868. /**
  34869. * Creates a new index buffer
  34870. * @param indices defines the indices to store in the index buffer
  34871. * @param totalVertices defines the total number of vertices (could be null)
  34872. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34873. */
  34874. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34875. if (totalVertices === void 0) { totalVertices = null; }
  34876. if (updatable === void 0) { updatable = false; }
  34877. if (this._indexBuffer) {
  34878. this._engine._releaseBuffer(this._indexBuffer);
  34879. }
  34880. this._disposeVertexArrayObjects();
  34881. this._indices = indices;
  34882. this._indexBufferIsUpdatable = updatable;
  34883. if (this._meshes.length !== 0 && this._indices) {
  34884. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34885. }
  34886. if (totalVertices != undefined) {
  34887. this._totalVertices = totalVertices;
  34888. }
  34889. var meshes = this._meshes;
  34890. var numOfMeshes = meshes.length;
  34891. for (var index = 0; index < numOfMeshes; index++) {
  34892. meshes[index]._createGlobalSubMesh(true);
  34893. }
  34894. this.notifyUpdate();
  34895. };
  34896. /**
  34897. * Return the total number of indices
  34898. * @returns the total number of indices
  34899. */
  34900. Geometry.prototype.getTotalIndices = function () {
  34901. if (!this.isReady()) {
  34902. return 0;
  34903. }
  34904. return this._indices.length;
  34905. };
  34906. /**
  34907. * Gets the index buffer array
  34908. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34909. * @returns the index buffer array
  34910. */
  34911. Geometry.prototype.getIndices = function (copyWhenShared) {
  34912. if (!this.isReady()) {
  34913. return null;
  34914. }
  34915. var orig = this._indices;
  34916. if (!copyWhenShared || this._meshes.length === 1) {
  34917. return orig;
  34918. }
  34919. else {
  34920. var len = orig.length;
  34921. var copy = [];
  34922. for (var i = 0; i < len; i++) {
  34923. copy.push(orig[i]);
  34924. }
  34925. return copy;
  34926. }
  34927. };
  34928. /**
  34929. * Gets the index buffer
  34930. * @return the index buffer
  34931. */
  34932. Geometry.prototype.getIndexBuffer = function () {
  34933. if (!this.isReady()) {
  34934. return null;
  34935. }
  34936. return this._indexBuffer;
  34937. };
  34938. /** @ignore */
  34939. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34940. if (effect === void 0) { effect = null; }
  34941. if (!effect || !this._vertexArrayObjects) {
  34942. return;
  34943. }
  34944. if (this._vertexArrayObjects[effect.key]) {
  34945. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34946. delete this._vertexArrayObjects[effect.key];
  34947. }
  34948. };
  34949. /**
  34950. * Release the associated resources for a specific mesh
  34951. * @param mesh defines the source mesh
  34952. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34953. */
  34954. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34955. var meshes = this._meshes;
  34956. var index = meshes.indexOf(mesh);
  34957. if (index === -1) {
  34958. return;
  34959. }
  34960. meshes.splice(index, 1);
  34961. mesh._geometry = null;
  34962. if (meshes.length === 0 && shouldDispose) {
  34963. this.dispose();
  34964. }
  34965. };
  34966. /**
  34967. * Apply current geometry to a given mesh
  34968. * @param mesh defines the mesh to apply geometry to
  34969. */
  34970. Geometry.prototype.applyToMesh = function (mesh) {
  34971. if (mesh._geometry === this) {
  34972. return;
  34973. }
  34974. var previousGeometry = mesh._geometry;
  34975. if (previousGeometry) {
  34976. previousGeometry.releaseForMesh(mesh);
  34977. }
  34978. var meshes = this._meshes;
  34979. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34980. mesh._geometry = this;
  34981. this._scene.pushGeometry(this);
  34982. meshes.push(mesh);
  34983. if (this.isReady()) {
  34984. this._applyToMesh(mesh);
  34985. }
  34986. else {
  34987. mesh._boundingInfo = this._boundingInfo;
  34988. }
  34989. };
  34990. Geometry.prototype.updateExtend = function (data, stride) {
  34991. if (data === void 0) { data = null; }
  34992. if (!data) {
  34993. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34994. }
  34995. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34996. };
  34997. Geometry.prototype._applyToMesh = function (mesh) {
  34998. var numOfMeshes = this._meshes.length;
  34999. // vertexBuffers
  35000. for (var kind in this._vertexBuffers) {
  35001. if (numOfMeshes === 1) {
  35002. this._vertexBuffers[kind].create();
  35003. }
  35004. var buffer = this._vertexBuffers[kind].getBuffer();
  35005. if (buffer)
  35006. buffer.references = numOfMeshes;
  35007. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35008. if (!this._extend) {
  35009. this.updateExtend(this._vertexBuffers[kind].getData());
  35010. }
  35011. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35012. mesh._createGlobalSubMesh(false);
  35013. //bounding info was just created again, world matrix should be applied again.
  35014. mesh._updateBoundingInfo();
  35015. }
  35016. }
  35017. // indexBuffer
  35018. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35019. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35020. }
  35021. if (this._indexBuffer) {
  35022. this._indexBuffer.references = numOfMeshes;
  35023. }
  35024. };
  35025. Geometry.prototype.notifyUpdate = function (kind) {
  35026. if (this.onGeometryUpdated) {
  35027. this.onGeometryUpdated(this, kind);
  35028. }
  35029. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35030. var mesh = _a[_i];
  35031. mesh._markSubMeshesAsAttributesDirty();
  35032. }
  35033. };
  35034. /**
  35035. * Load the geometry if it was flagged as delay loaded
  35036. * @param scene defines the hosting scene
  35037. * @param onLoaded defines a callback called when the geometry is loaded
  35038. */
  35039. Geometry.prototype.load = function (scene, onLoaded) {
  35040. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35041. return;
  35042. }
  35043. if (this.isReady()) {
  35044. if (onLoaded) {
  35045. onLoaded();
  35046. }
  35047. return;
  35048. }
  35049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35050. this._queueLoad(scene, onLoaded);
  35051. };
  35052. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35053. var _this = this;
  35054. if (!this.delayLoadingFile) {
  35055. return;
  35056. }
  35057. scene._addPendingData(this);
  35058. scene._loadFile(this.delayLoadingFile, function (data) {
  35059. if (!_this._delayLoadingFunction) {
  35060. return;
  35061. }
  35062. _this._delayLoadingFunction(JSON.parse(data), _this);
  35063. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35064. _this._delayInfo = [];
  35065. scene._removePendingData(_this);
  35066. var meshes = _this._meshes;
  35067. var numOfMeshes = meshes.length;
  35068. for (var index = 0; index < numOfMeshes; index++) {
  35069. _this._applyToMesh(meshes[index]);
  35070. }
  35071. if (onLoaded) {
  35072. onLoaded();
  35073. }
  35074. }, undefined, true);
  35075. };
  35076. /**
  35077. * Invert the geometry to move from a right handed system to a left handed one.
  35078. */
  35079. Geometry.prototype.toLeftHanded = function () {
  35080. // Flip faces
  35081. var tIndices = this.getIndices(false);
  35082. if (tIndices != null && tIndices.length > 0) {
  35083. for (var i = 0; i < tIndices.length; i += 3) {
  35084. var tTemp = tIndices[i + 0];
  35085. tIndices[i + 0] = tIndices[i + 2];
  35086. tIndices[i + 2] = tTemp;
  35087. }
  35088. this.setIndices(tIndices);
  35089. }
  35090. // Negate position.z
  35091. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35092. if (tPositions != null && tPositions.length > 0) {
  35093. for (var i = 0; i < tPositions.length; i += 3) {
  35094. tPositions[i + 2] = -tPositions[i + 2];
  35095. }
  35096. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35097. }
  35098. // Negate normal.z
  35099. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35100. if (tNormals != null && tNormals.length > 0) {
  35101. for (var i = 0; i < tNormals.length; i += 3) {
  35102. tNormals[i + 2] = -tNormals[i + 2];
  35103. }
  35104. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35105. }
  35106. };
  35107. // Cache
  35108. /** @ignore */
  35109. Geometry.prototype._resetPointsArrayCache = function () {
  35110. this._positions = null;
  35111. };
  35112. /** @ignore */
  35113. Geometry.prototype._generatePointsArray = function () {
  35114. if (this._positions)
  35115. return true;
  35116. this._positions = [];
  35117. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35118. if (!data) {
  35119. return false;
  35120. }
  35121. for (var index = 0; index < data.length; index += 3) {
  35122. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35123. }
  35124. return true;
  35125. };
  35126. /**
  35127. * Gets a value indicating if the geometry is disposed
  35128. * @returns true if the geometry was disposed
  35129. */
  35130. Geometry.prototype.isDisposed = function () {
  35131. return this._isDisposed;
  35132. };
  35133. Geometry.prototype._disposeVertexArrayObjects = function () {
  35134. if (this._vertexArrayObjects) {
  35135. for (var kind in this._vertexArrayObjects) {
  35136. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35137. }
  35138. this._vertexArrayObjects = {};
  35139. }
  35140. };
  35141. /**
  35142. * Free all associated resources
  35143. */
  35144. Geometry.prototype.dispose = function () {
  35145. var meshes = this._meshes;
  35146. var numOfMeshes = meshes.length;
  35147. var index;
  35148. for (index = 0; index < numOfMeshes; index++) {
  35149. this.releaseForMesh(meshes[index]);
  35150. }
  35151. this._meshes = [];
  35152. this._disposeVertexArrayObjects();
  35153. for (var kind in this._vertexBuffers) {
  35154. this._vertexBuffers[kind].dispose();
  35155. }
  35156. this._vertexBuffers = {};
  35157. this._totalVertices = 0;
  35158. if (this._indexBuffer) {
  35159. this._engine._releaseBuffer(this._indexBuffer);
  35160. }
  35161. this._indexBuffer = null;
  35162. this._indices = [];
  35163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35164. this.delayLoadingFile = null;
  35165. this._delayLoadingFunction = null;
  35166. this._delayInfo = [];
  35167. this._boundingInfo = null;
  35168. this._scene.removeGeometry(this);
  35169. this._isDisposed = true;
  35170. };
  35171. /**
  35172. * Clone the current geometry into a new geometry
  35173. * @param id defines the unique ID of the new geometry
  35174. * @returns a new geometry object
  35175. */
  35176. Geometry.prototype.copy = function (id) {
  35177. var vertexData = new BABYLON.VertexData();
  35178. vertexData.indices = [];
  35179. var indices = this.getIndices();
  35180. if (indices) {
  35181. for (var index = 0; index < indices.length; index++) {
  35182. vertexData.indices.push(indices[index]);
  35183. }
  35184. }
  35185. var updatable = false;
  35186. var stopChecking = false;
  35187. var kind;
  35188. for (kind in this._vertexBuffers) {
  35189. // using slice() to make a copy of the array and not just reference it
  35190. var data = this.getVerticesData(kind);
  35191. if (data instanceof Float32Array) {
  35192. vertexData.set(new Float32Array(data), kind);
  35193. }
  35194. else {
  35195. vertexData.set(data.slice(0), kind);
  35196. }
  35197. if (!stopChecking) {
  35198. var vb = this.getVertexBuffer(kind);
  35199. if (vb) {
  35200. updatable = vb.isUpdatable();
  35201. stopChecking = !updatable;
  35202. }
  35203. }
  35204. }
  35205. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35206. geometry.delayLoadState = this.delayLoadState;
  35207. geometry.delayLoadingFile = this.delayLoadingFile;
  35208. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35209. for (kind in this._delayInfo) {
  35210. geometry._delayInfo = geometry._delayInfo || [];
  35211. geometry._delayInfo.push(kind);
  35212. }
  35213. // Bounding info
  35214. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35215. return geometry;
  35216. };
  35217. /**
  35218. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35219. * @return a JSON representation of the current geometry data (without the vertices data)
  35220. */
  35221. Geometry.prototype.serialize = function () {
  35222. var serializationObject = {};
  35223. serializationObject.id = this.id;
  35224. serializationObject.updatable = this._updatable;
  35225. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35226. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35227. }
  35228. return serializationObject;
  35229. };
  35230. Geometry.prototype.toNumberArray = function (origin) {
  35231. if (Array.isArray(origin)) {
  35232. return origin;
  35233. }
  35234. else {
  35235. return Array.prototype.slice.call(origin);
  35236. }
  35237. };
  35238. /**
  35239. * Serialize all vertices data into a JSON oject
  35240. * @returns a JSON representation of the current geometry data
  35241. */
  35242. Geometry.prototype.serializeVerticeData = function () {
  35243. var serializationObject = this.serialize();
  35244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35245. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35246. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35247. serializationObject.positions._updatable = true;
  35248. }
  35249. }
  35250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35251. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35252. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35253. serializationObject.normals._updatable = true;
  35254. }
  35255. }
  35256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35257. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35259. serializationObject.tangets._updatable = true;
  35260. }
  35261. }
  35262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35263. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35264. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35265. serializationObject.uvs._updatable = true;
  35266. }
  35267. }
  35268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35269. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35271. serializationObject.uv2s._updatable = true;
  35272. }
  35273. }
  35274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35275. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35277. serializationObject.uv3s._updatable = true;
  35278. }
  35279. }
  35280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35281. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35282. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35283. serializationObject.uv4s._updatable = true;
  35284. }
  35285. }
  35286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35287. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35288. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35289. serializationObject.uv5s._updatable = true;
  35290. }
  35291. }
  35292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35293. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35294. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35295. serializationObject.uv6s._updatable = true;
  35296. }
  35297. }
  35298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35299. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35300. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35301. serializationObject.colors._updatable = true;
  35302. }
  35303. }
  35304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35305. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35306. serializationObject.matricesIndices._isExpanded = true;
  35307. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35308. serializationObject.matricesIndices._updatable = true;
  35309. }
  35310. }
  35311. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35312. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35313. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35314. serializationObject.matricesWeights._updatable = true;
  35315. }
  35316. }
  35317. serializationObject.indices = this.toNumberArray(this.getIndices());
  35318. return serializationObject;
  35319. };
  35320. // Statics
  35321. /**
  35322. * Extracts a clone of a mesh geometry
  35323. * @param mesh defines the source mesh
  35324. * @param id defines the unique ID of the new geometry object
  35325. * @returns the new geometry object
  35326. */
  35327. Geometry.ExtractFromMesh = function (mesh, id) {
  35328. var geometry = mesh._geometry;
  35329. if (!geometry) {
  35330. return null;
  35331. }
  35332. return geometry.copy(id);
  35333. };
  35334. /**
  35335. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35336. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35337. * Be aware Math.random() could cause collisions, but:
  35338. * "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"
  35339. * @returns a string containing a new GUID
  35340. */
  35341. Geometry.RandomId = function () {
  35342. return BABYLON.Tools.RandomId();
  35343. };
  35344. /** @ignore */
  35345. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35346. var scene = mesh.getScene();
  35347. // Geometry
  35348. var geometryId = parsedGeometry.geometryId;
  35349. if (geometryId) {
  35350. var geometry = scene.getGeometryByID(geometryId);
  35351. if (geometry) {
  35352. geometry.applyToMesh(mesh);
  35353. }
  35354. }
  35355. else if (parsedGeometry instanceof ArrayBuffer) {
  35356. var binaryInfo = mesh._binaryInfo;
  35357. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35358. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35359. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35360. }
  35361. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35362. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35363. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35364. }
  35365. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35366. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35367. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35368. }
  35369. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35370. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35371. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35372. }
  35373. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35374. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35375. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35376. }
  35377. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35378. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35379. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35380. }
  35381. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35382. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35383. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35384. }
  35385. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35386. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35387. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35388. }
  35389. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35390. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35391. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35392. }
  35393. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35394. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35395. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35396. }
  35397. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35398. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35399. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35400. }
  35401. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35402. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35404. }
  35405. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35406. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35407. mesh.setIndices(indicesData, null);
  35408. }
  35409. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35410. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35411. mesh.subMeshes = [];
  35412. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35413. var materialIndex = subMeshesData[(i * 5) + 0];
  35414. var verticesStart = subMeshesData[(i * 5) + 1];
  35415. var verticesCount = subMeshesData[(i * 5) + 2];
  35416. var indexStart = subMeshesData[(i * 5) + 3];
  35417. var indexCount = subMeshesData[(i * 5) + 4];
  35418. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35419. }
  35420. }
  35421. }
  35422. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35423. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35424. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35425. if (parsedGeometry.tangents) {
  35426. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35427. }
  35428. if (parsedGeometry.uvs) {
  35429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35430. }
  35431. if (parsedGeometry.uvs2) {
  35432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35433. }
  35434. if (parsedGeometry.uvs3) {
  35435. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35436. }
  35437. if (parsedGeometry.uvs4) {
  35438. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35439. }
  35440. if (parsedGeometry.uvs5) {
  35441. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35442. }
  35443. if (parsedGeometry.uvs6) {
  35444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35445. }
  35446. if (parsedGeometry.colors) {
  35447. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35448. }
  35449. if (parsedGeometry.matricesIndices) {
  35450. if (!parsedGeometry.matricesIndices._isExpanded) {
  35451. var floatIndices = [];
  35452. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35453. var matricesIndex = parsedGeometry.matricesIndices[i];
  35454. floatIndices.push(matricesIndex & 0x000000FF);
  35455. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35456. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35457. floatIndices.push(matricesIndex >> 24);
  35458. }
  35459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35460. }
  35461. else {
  35462. delete parsedGeometry.matricesIndices._isExpanded;
  35463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35464. }
  35465. }
  35466. if (parsedGeometry.matricesIndicesExtra) {
  35467. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35468. var floatIndices = [];
  35469. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35470. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35471. floatIndices.push(matricesIndex & 0x000000FF);
  35472. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35473. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35474. floatIndices.push(matricesIndex >> 24);
  35475. }
  35476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35477. }
  35478. else {
  35479. delete parsedGeometry.matricesIndices._isExpanded;
  35480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35481. }
  35482. }
  35483. if (parsedGeometry.matricesWeights) {
  35484. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35486. }
  35487. if (parsedGeometry.matricesWeightsExtra) {
  35488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35489. }
  35490. mesh.setIndices(parsedGeometry.indices, null);
  35491. }
  35492. // SubMeshes
  35493. if (parsedGeometry.subMeshes) {
  35494. mesh.subMeshes = [];
  35495. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35496. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35497. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35498. }
  35499. }
  35500. // Flat shading
  35501. if (mesh._shouldGenerateFlatShading) {
  35502. mesh.convertToFlatShadedMesh();
  35503. delete mesh._shouldGenerateFlatShading;
  35504. }
  35505. // Update
  35506. mesh.computeWorldMatrix(true);
  35507. // Octree
  35508. var sceneOctree = scene.selectionOctree;
  35509. if (sceneOctree !== undefined && sceneOctree !== null) {
  35510. sceneOctree.addMesh(mesh);
  35511. }
  35512. };
  35513. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35514. var epsilon = 1e-3;
  35515. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35516. return;
  35517. }
  35518. var noInfluenceBoneIndex = 0.0;
  35519. if (parsedGeometry.skeletonId > -1) {
  35520. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35521. if (!skeleton) {
  35522. return;
  35523. }
  35524. noInfluenceBoneIndex = skeleton.bones.length;
  35525. }
  35526. else {
  35527. return;
  35528. }
  35529. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35530. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35531. var matricesWeights = parsedGeometry.matricesWeights;
  35532. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35533. var influencers = parsedGeometry.numBoneInfluencer;
  35534. var size = matricesWeights.length;
  35535. for (var i = 0; i < size; i += 4) {
  35536. var weight = 0.0;
  35537. var firstZeroWeight = -1;
  35538. for (var j = 0; j < 4; j++) {
  35539. var w = matricesWeights[i + j];
  35540. weight += w;
  35541. if (w < epsilon && firstZeroWeight < 0) {
  35542. firstZeroWeight = j;
  35543. }
  35544. }
  35545. if (matricesWeightsExtra) {
  35546. for (var j = 0; j < 4; j++) {
  35547. var w = matricesWeightsExtra[i + j];
  35548. weight += w;
  35549. if (w < epsilon && firstZeroWeight < 0) {
  35550. firstZeroWeight = j + 4;
  35551. }
  35552. }
  35553. }
  35554. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35555. firstZeroWeight = influencers - 1;
  35556. }
  35557. if (weight > epsilon) {
  35558. var mweight = 1.0 / weight;
  35559. for (var j = 0; j < 4; j++) {
  35560. matricesWeights[i + j] *= mweight;
  35561. }
  35562. if (matricesWeightsExtra) {
  35563. for (var j = 0; j < 4; j++) {
  35564. matricesWeightsExtra[i + j] *= mweight;
  35565. }
  35566. }
  35567. }
  35568. else {
  35569. if (firstZeroWeight >= 4) {
  35570. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35571. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35572. }
  35573. else {
  35574. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35575. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35576. }
  35577. }
  35578. }
  35579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35580. if (parsedGeometry.matricesWeightsExtra) {
  35581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35582. }
  35583. };
  35584. /**
  35585. * Create a new geometry from persisted data (Using .babylon file format)
  35586. * @param parsedVertexData defines the persisted data
  35587. * @param scene defines the hosting scene
  35588. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35589. * @returns the new geometry object
  35590. */
  35591. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35592. if (scene.getGeometryByID(parsedVertexData.id)) {
  35593. return null; // null since geometry could be something else than a box...
  35594. }
  35595. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35596. if (BABYLON.Tags) {
  35597. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35598. }
  35599. if (parsedVertexData.delayLoadingFile) {
  35600. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35601. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35602. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35603. geometry._delayInfo = [];
  35604. if (parsedVertexData.hasUVs) {
  35605. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35606. }
  35607. if (parsedVertexData.hasUVs2) {
  35608. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35609. }
  35610. if (parsedVertexData.hasUVs3) {
  35611. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35612. }
  35613. if (parsedVertexData.hasUVs4) {
  35614. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35615. }
  35616. if (parsedVertexData.hasUVs5) {
  35617. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35618. }
  35619. if (parsedVertexData.hasUVs6) {
  35620. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35621. }
  35622. if (parsedVertexData.hasColors) {
  35623. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35624. }
  35625. if (parsedVertexData.hasMatricesIndices) {
  35626. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35627. }
  35628. if (parsedVertexData.hasMatricesWeights) {
  35629. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35630. }
  35631. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35632. }
  35633. else {
  35634. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35635. }
  35636. scene.pushGeometry(geometry, true);
  35637. return geometry;
  35638. };
  35639. return Geometry;
  35640. }());
  35641. BABYLON.Geometry = Geometry;
  35642. // Primitives
  35643. /// Abstract class
  35644. /**
  35645. * Abstract class used to provide common services for all typed geometries
  35646. */
  35647. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35648. __extends(_PrimitiveGeometry, _super);
  35649. /**
  35650. * Creates a new typed geometry
  35651. * @param id defines the unique ID of the geometry
  35652. * @param scene defines the hosting scene
  35653. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35654. * @param mesh defines the hosting mesh (can be null)
  35655. */
  35656. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35657. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35658. if (mesh === void 0) { mesh = null; }
  35659. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35660. _this._canBeRegenerated = _canBeRegenerated;
  35661. _this._beingRegenerated = true;
  35662. _this.regenerate();
  35663. _this._beingRegenerated = false;
  35664. return _this;
  35665. }
  35666. /**
  35667. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35668. * @returns true if the geometry can be regenerated
  35669. */
  35670. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35671. return this._canBeRegenerated;
  35672. };
  35673. /**
  35674. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35675. */
  35676. _PrimitiveGeometry.prototype.regenerate = function () {
  35677. if (!this._canBeRegenerated) {
  35678. return;
  35679. }
  35680. this._beingRegenerated = true;
  35681. this.setAllVerticesData(this._regenerateVertexData(), false);
  35682. this._beingRegenerated = false;
  35683. };
  35684. /**
  35685. * Clone the geometry
  35686. * @param id defines the unique ID of the new geometry
  35687. * @returns the new geometry
  35688. */
  35689. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35690. return _super.prototype.copy.call(this, id);
  35691. };
  35692. // overrides
  35693. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35694. if (!this._beingRegenerated) {
  35695. return;
  35696. }
  35697. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35698. };
  35699. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35700. if (!this._beingRegenerated) {
  35701. return;
  35702. }
  35703. _super.prototype.setVerticesData.call(this, kind, data, false);
  35704. };
  35705. // to override
  35706. /** @ignore */
  35707. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35708. throw new Error("Abstract method");
  35709. };
  35710. _PrimitiveGeometry.prototype.copy = function (id) {
  35711. throw new Error("Must be overriden in sub-classes.");
  35712. };
  35713. _PrimitiveGeometry.prototype.serialize = function () {
  35714. var serializationObject = _super.prototype.serialize.call(this);
  35715. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35716. return serializationObject;
  35717. };
  35718. return _PrimitiveGeometry;
  35719. }(Geometry));
  35720. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35721. /**
  35722. * Creates a ribbon geometry
  35723. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35724. */
  35725. var RibbonGeometry = /** @class */ (function (_super) {
  35726. __extends(RibbonGeometry, _super);
  35727. /**
  35728. * Creates a ribbon geometry
  35729. * @param id defines the unique ID of the geometry
  35730. * @param scene defines the hosting scene
  35731. * @param pathArray defines the array of paths to use
  35732. * @param closeArray defines if the last path and the first path must be joined
  35733. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35734. * @param offset defines the offset between points
  35735. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35736. * @param mesh defines the hosting mesh (can be null)
  35737. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35738. */
  35739. function RibbonGeometry(id, scene,
  35740. /**
  35741. * Defines the array of paths to use
  35742. */
  35743. pathArray,
  35744. /**
  35745. * Defines if the last and first points of each path in your pathArray must be joined
  35746. */
  35747. closeArray,
  35748. /**
  35749. * Defines if the last and first points of each path in your pathArray must be joined
  35750. */
  35751. closePath,
  35752. /**
  35753. * Defines the offset between points
  35754. */
  35755. offset, canBeRegenerated, mesh,
  35756. /**
  35757. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35758. */
  35759. side) {
  35760. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35761. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35762. _this.pathArray = pathArray;
  35763. _this.closeArray = closeArray;
  35764. _this.closePath = closePath;
  35765. _this.offset = offset;
  35766. _this.side = side;
  35767. return _this;
  35768. }
  35769. /** @ignore */
  35770. RibbonGeometry.prototype._regenerateVertexData = function () {
  35771. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35772. };
  35773. RibbonGeometry.prototype.copy = function (id) {
  35774. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35775. };
  35776. return RibbonGeometry;
  35777. }(_PrimitiveGeometry));
  35778. BABYLON.RibbonGeometry = RibbonGeometry;
  35779. /**
  35780. * Creates a box geometry
  35781. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35782. */
  35783. var BoxGeometry = /** @class */ (function (_super) {
  35784. __extends(BoxGeometry, _super);
  35785. /**
  35786. * Creates a box geometry
  35787. * @param id defines the unique ID of the geometry
  35788. * @param scene defines the hosting scene
  35789. * @param size defines the zise of the box (width, height and depth are the same)
  35790. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35791. * @param mesh defines the hosting mesh (can be null)
  35792. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35793. */
  35794. function BoxGeometry(id, scene,
  35795. /**
  35796. * Defines the zise of the box (width, height and depth are the same)
  35797. */
  35798. size, canBeRegenerated, mesh,
  35799. /**
  35800. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35801. */
  35802. side) {
  35803. if (mesh === void 0) { mesh = null; }
  35804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35806. _this.size = size;
  35807. _this.side = side;
  35808. return _this;
  35809. }
  35810. BoxGeometry.prototype._regenerateVertexData = function () {
  35811. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35812. };
  35813. BoxGeometry.prototype.copy = function (id) {
  35814. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35815. };
  35816. BoxGeometry.prototype.serialize = function () {
  35817. var serializationObject = _super.prototype.serialize.call(this);
  35818. serializationObject.size = this.size;
  35819. return serializationObject;
  35820. };
  35821. BoxGeometry.Parse = function (parsedBox, scene) {
  35822. if (scene.getGeometryByID(parsedBox.id)) {
  35823. return null; // null since geometry could be something else than a box...
  35824. }
  35825. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35826. if (BABYLON.Tags) {
  35827. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35828. }
  35829. scene.pushGeometry(box, true);
  35830. return box;
  35831. };
  35832. return BoxGeometry;
  35833. }(_PrimitiveGeometry));
  35834. BABYLON.BoxGeometry = BoxGeometry;
  35835. /**
  35836. * Creates a sphere geometry
  35837. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35838. */
  35839. var SphereGeometry = /** @class */ (function (_super) {
  35840. __extends(SphereGeometry, _super);
  35841. /**
  35842. * Create a new sphere geometry
  35843. * @param id defines the unique ID of the geometry
  35844. * @param scene defines the hosting scene
  35845. * @param segments defines the number of segments to use to create the sphere
  35846. * @param diameter defines the diameter of the sphere
  35847. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35848. * @param mesh defines the hosting mesh (can be null)
  35849. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. function SphereGeometry(id, scene,
  35852. /**
  35853. * Defines the number of segments to use to create the sphere
  35854. */
  35855. segments,
  35856. /**
  35857. * Defines the diameter of the sphere
  35858. */
  35859. diameter, canBeRegenerated, mesh,
  35860. /**
  35861. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35862. */
  35863. side) {
  35864. if (mesh === void 0) { mesh = null; }
  35865. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35866. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35867. _this.segments = segments;
  35868. _this.diameter = diameter;
  35869. _this.side = side;
  35870. return _this;
  35871. }
  35872. SphereGeometry.prototype._regenerateVertexData = function () {
  35873. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35874. };
  35875. SphereGeometry.prototype.copy = function (id) {
  35876. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35877. };
  35878. SphereGeometry.prototype.serialize = function () {
  35879. var serializationObject = _super.prototype.serialize.call(this);
  35880. serializationObject.segments = this.segments;
  35881. serializationObject.diameter = this.diameter;
  35882. return serializationObject;
  35883. };
  35884. SphereGeometry.Parse = function (parsedSphere, scene) {
  35885. if (scene.getGeometryByID(parsedSphere.id)) {
  35886. return null; // null since geometry could be something else than a sphere...
  35887. }
  35888. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35889. if (BABYLON.Tags) {
  35890. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35891. }
  35892. scene.pushGeometry(sphere, true);
  35893. return sphere;
  35894. };
  35895. return SphereGeometry;
  35896. }(_PrimitiveGeometry));
  35897. BABYLON.SphereGeometry = SphereGeometry;
  35898. /**
  35899. * Creates a disc geometry
  35900. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35901. */
  35902. var DiscGeometry = /** @class */ (function (_super) {
  35903. __extends(DiscGeometry, _super);
  35904. /**
  35905. * Creates a new disc geometry
  35906. * @param id defines the unique ID of the geometry
  35907. * @param scene defines the hosting scene
  35908. * @param radius defines the radius of the disc
  35909. * @param tessellation defines the tesselation factor to apply to the disc
  35910. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35911. * @param mesh defines the hosting mesh (can be null)
  35912. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35913. */
  35914. function DiscGeometry(id, scene,
  35915. /**
  35916. * Defines the radius of the disc
  35917. */
  35918. radius,
  35919. /**
  35920. * Defines the tesselation factor to apply to the disc
  35921. */
  35922. tessellation, canBeRegenerated, mesh,
  35923. /**
  35924. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35925. */
  35926. side) {
  35927. if (mesh === void 0) { mesh = null; }
  35928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35930. _this.radius = radius;
  35931. _this.tessellation = tessellation;
  35932. _this.side = side;
  35933. return _this;
  35934. }
  35935. DiscGeometry.prototype._regenerateVertexData = function () {
  35936. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35937. };
  35938. DiscGeometry.prototype.copy = function (id) {
  35939. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35940. };
  35941. return DiscGeometry;
  35942. }(_PrimitiveGeometry));
  35943. BABYLON.DiscGeometry = DiscGeometry;
  35944. /**
  35945. * Creates a new cylinder geometry
  35946. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35947. */
  35948. var CylinderGeometry = /** @class */ (function (_super) {
  35949. __extends(CylinderGeometry, _super);
  35950. /**
  35951. * Creates a new cylinder geometry
  35952. * @param id defines the unique ID of the geometry
  35953. * @param scene defines the hosting scene
  35954. * @param height defines the height of the cylinder
  35955. * @param diameterTop defines the diameter of the cylinder's top cap
  35956. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35957. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35958. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35959. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35960. * @param mesh defines the hosting mesh (can be null)
  35961. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35962. */
  35963. function CylinderGeometry(id, scene,
  35964. /**
  35965. * Defines the height of the cylinder
  35966. */
  35967. height,
  35968. /**
  35969. * Defines the diameter of the cylinder's top cap
  35970. */
  35971. diameterTop,
  35972. /**
  35973. * Defines the diameter of the cylinder's bottom cap
  35974. */
  35975. diameterBottom,
  35976. /**
  35977. * Defines the tessellation factor to apply to the cylinder
  35978. */
  35979. tessellation,
  35980. /**
  35981. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35982. */
  35983. subdivisions, canBeRegenerated, mesh,
  35984. /**
  35985. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35986. */
  35987. side) {
  35988. if (subdivisions === void 0) { subdivisions = 1; }
  35989. if (mesh === void 0) { mesh = null; }
  35990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35992. _this.height = height;
  35993. _this.diameterTop = diameterTop;
  35994. _this.diameterBottom = diameterBottom;
  35995. _this.tessellation = tessellation;
  35996. _this.subdivisions = subdivisions;
  35997. _this.side = side;
  35998. return _this;
  35999. }
  36000. CylinderGeometry.prototype._regenerateVertexData = function () {
  36001. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36002. };
  36003. CylinderGeometry.prototype.copy = function (id) {
  36004. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36005. };
  36006. CylinderGeometry.prototype.serialize = function () {
  36007. var serializationObject = _super.prototype.serialize.call(this);
  36008. serializationObject.height = this.height;
  36009. serializationObject.diameterTop = this.diameterTop;
  36010. serializationObject.diameterBottom = this.diameterBottom;
  36011. serializationObject.tessellation = this.tessellation;
  36012. return serializationObject;
  36013. };
  36014. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36015. if (scene.getGeometryByID(parsedCylinder.id)) {
  36016. return null; // null since geometry could be something else than a cylinder...
  36017. }
  36018. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36019. if (BABYLON.Tags) {
  36020. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36021. }
  36022. scene.pushGeometry(cylinder, true);
  36023. return cylinder;
  36024. };
  36025. return CylinderGeometry;
  36026. }(_PrimitiveGeometry));
  36027. BABYLON.CylinderGeometry = CylinderGeometry;
  36028. /**
  36029. * Creates a new torus geometry
  36030. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36031. */
  36032. var TorusGeometry = /** @class */ (function (_super) {
  36033. __extends(TorusGeometry, _super);
  36034. /**
  36035. * Creates a new torus geometry
  36036. * @param id defines the unique ID of the geometry
  36037. * @param scene defines the hosting scene
  36038. * @param diameter defines the diameter of the torus
  36039. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36040. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36041. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36042. * @param mesh defines the hosting mesh (can be null)
  36043. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36044. */
  36045. function TorusGeometry(id, scene,
  36046. /**
  36047. * Defines the diameter of the torus
  36048. */
  36049. diameter,
  36050. /**
  36051. * Defines the thickness of the torus (ie. internal diameter)
  36052. */
  36053. thickness,
  36054. /**
  36055. * Defines the tesselation factor to apply to the torus
  36056. */
  36057. tessellation, canBeRegenerated, mesh,
  36058. /**
  36059. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36060. */
  36061. side) {
  36062. if (mesh === void 0) { mesh = null; }
  36063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36065. _this.diameter = diameter;
  36066. _this.thickness = thickness;
  36067. _this.tessellation = tessellation;
  36068. _this.side = side;
  36069. return _this;
  36070. }
  36071. TorusGeometry.prototype._regenerateVertexData = function () {
  36072. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36073. };
  36074. TorusGeometry.prototype.copy = function (id) {
  36075. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36076. };
  36077. TorusGeometry.prototype.serialize = function () {
  36078. var serializationObject = _super.prototype.serialize.call(this);
  36079. serializationObject.diameter = this.diameter;
  36080. serializationObject.thickness = this.thickness;
  36081. serializationObject.tessellation = this.tessellation;
  36082. return serializationObject;
  36083. };
  36084. TorusGeometry.Parse = function (parsedTorus, scene) {
  36085. if (scene.getGeometryByID(parsedTorus.id)) {
  36086. return null; // null since geometry could be something else than a torus...
  36087. }
  36088. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36089. if (BABYLON.Tags) {
  36090. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36091. }
  36092. scene.pushGeometry(torus, true);
  36093. return torus;
  36094. };
  36095. return TorusGeometry;
  36096. }(_PrimitiveGeometry));
  36097. BABYLON.TorusGeometry = TorusGeometry;
  36098. /**
  36099. * Creates a new ground geometry
  36100. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36101. */
  36102. var GroundGeometry = /** @class */ (function (_super) {
  36103. __extends(GroundGeometry, _super);
  36104. /**
  36105. * Creates a new ground geometry
  36106. * @param id defines the unique ID of the geometry
  36107. * @param scene defines the hosting scene
  36108. * @param width defines the width of the ground
  36109. * @param height defines the height of the ground
  36110. * @param subdivisions defines the subdivisions to apply to the ground
  36111. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36112. * @param mesh defines the hosting mesh (can be null)
  36113. */
  36114. function GroundGeometry(id, scene,
  36115. /**
  36116. * Defines the width of the ground
  36117. */
  36118. width,
  36119. /**
  36120. * Defines the height of the ground
  36121. */
  36122. height,
  36123. /**
  36124. * Defines the subdivisions to apply to the ground
  36125. */
  36126. subdivisions, canBeRegenerated, mesh) {
  36127. if (mesh === void 0) { mesh = null; }
  36128. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36129. _this.width = width;
  36130. _this.height = height;
  36131. _this.subdivisions = subdivisions;
  36132. return _this;
  36133. }
  36134. GroundGeometry.prototype._regenerateVertexData = function () {
  36135. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36136. };
  36137. GroundGeometry.prototype.copy = function (id) {
  36138. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36139. };
  36140. GroundGeometry.prototype.serialize = function () {
  36141. var serializationObject = _super.prototype.serialize.call(this);
  36142. serializationObject.width = this.width;
  36143. serializationObject.height = this.height;
  36144. serializationObject.subdivisions = this.subdivisions;
  36145. return serializationObject;
  36146. };
  36147. GroundGeometry.Parse = function (parsedGround, scene) {
  36148. if (scene.getGeometryByID(parsedGround.id)) {
  36149. return null; // null since geometry could be something else than a ground...
  36150. }
  36151. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36152. if (BABYLON.Tags) {
  36153. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36154. }
  36155. scene.pushGeometry(ground, true);
  36156. return ground;
  36157. };
  36158. return GroundGeometry;
  36159. }(_PrimitiveGeometry));
  36160. BABYLON.GroundGeometry = GroundGeometry;
  36161. /**
  36162. * Creates a tiled ground geometry
  36163. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36164. */
  36165. var TiledGroundGeometry = /** @class */ (function (_super) {
  36166. __extends(TiledGroundGeometry, _super);
  36167. /**
  36168. * Creates a tiled ground geometry
  36169. * @param id defines the unique ID of the geometry
  36170. * @param scene defines the hosting scene
  36171. * @param xmin defines the minimum value on X axis
  36172. * @param zmin defines the minimum value on Z axis
  36173. * @param xmax defines the maximum value on X axis
  36174. * @param zmax defines the maximum value on Z axis
  36175. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36176. * @param precision defines the precision to use when computing the tiles
  36177. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36178. * @param mesh defines the hosting mesh (can be null)
  36179. */
  36180. function TiledGroundGeometry(id, scene,
  36181. /**
  36182. * Defines the minimum value on X axis
  36183. */
  36184. xmin,
  36185. /**
  36186. * Defines the minimum value on Z axis
  36187. */
  36188. zmin,
  36189. /**
  36190. * Defines the maximum value on X axis
  36191. */
  36192. xmax,
  36193. /**
  36194. * Defines the maximum value on Z axis
  36195. */
  36196. zmax,
  36197. /**
  36198. * Defines the subdivisions to apply to the ground
  36199. */
  36200. subdivisions,
  36201. /**
  36202. * Defines the precision to use when computing the tiles
  36203. */
  36204. precision, canBeRegenerated, mesh) {
  36205. if (mesh === void 0) { mesh = null; }
  36206. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36207. _this.xmin = xmin;
  36208. _this.zmin = zmin;
  36209. _this.xmax = xmax;
  36210. _this.zmax = zmax;
  36211. _this.subdivisions = subdivisions;
  36212. _this.precision = precision;
  36213. return _this;
  36214. }
  36215. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36216. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36217. };
  36218. TiledGroundGeometry.prototype.copy = function (id) {
  36219. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36220. };
  36221. return TiledGroundGeometry;
  36222. }(_PrimitiveGeometry));
  36223. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36224. /**
  36225. * Creates a plane geometry
  36226. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36227. */
  36228. var PlaneGeometry = /** @class */ (function (_super) {
  36229. __extends(PlaneGeometry, _super);
  36230. /**
  36231. * Creates a plane geometry
  36232. * @param id defines the unique ID of the geometry
  36233. * @param scene defines the hosting scene
  36234. * @param size defines the size of the plane (width === height)
  36235. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36236. * @param mesh defines the hosting mesh (can be null)
  36237. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36238. */
  36239. function PlaneGeometry(id, scene,
  36240. /**
  36241. * Defines the size of the plane (width === height)
  36242. */
  36243. size, canBeRegenerated, mesh,
  36244. /**
  36245. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36246. */
  36247. side) {
  36248. if (mesh === void 0) { mesh = null; }
  36249. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36250. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36251. _this.size = size;
  36252. _this.side = side;
  36253. return _this;
  36254. }
  36255. PlaneGeometry.prototype._regenerateVertexData = function () {
  36256. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36257. };
  36258. PlaneGeometry.prototype.copy = function (id) {
  36259. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36260. };
  36261. PlaneGeometry.prototype.serialize = function () {
  36262. var serializationObject = _super.prototype.serialize.call(this);
  36263. serializationObject.size = this.size;
  36264. return serializationObject;
  36265. };
  36266. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36267. if (scene.getGeometryByID(parsedPlane.id)) {
  36268. return null; // null since geometry could be something else than a ground...
  36269. }
  36270. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36271. if (BABYLON.Tags) {
  36272. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36273. }
  36274. scene.pushGeometry(plane, true);
  36275. return plane;
  36276. };
  36277. return PlaneGeometry;
  36278. }(_PrimitiveGeometry));
  36279. BABYLON.PlaneGeometry = PlaneGeometry;
  36280. /**
  36281. * Creates a torus knot geometry
  36282. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36283. */
  36284. var TorusKnotGeometry = /** @class */ (function (_super) {
  36285. __extends(TorusKnotGeometry, _super);
  36286. /**
  36287. * Creates a torus knot geometry
  36288. * @param id defines the unique ID of the geometry
  36289. * @param scene defines the hosting scene
  36290. * @param radius defines the radius of the torus knot
  36291. * @param tube defines the thickness of the torus knot tube
  36292. * @param radialSegments defines the number of radial segments
  36293. * @param tubularSegments defines the number of tubular segments
  36294. * @param p defines the first number of windings
  36295. * @param q defines the second number of windings
  36296. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36297. * @param mesh defines the hosting mesh (can be null)
  36298. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36299. */
  36300. function TorusKnotGeometry(id, scene,
  36301. /**
  36302. * Defines the radius of the torus knot
  36303. */
  36304. radius,
  36305. /**
  36306. * Defines the thickness of the torus knot tube
  36307. */
  36308. tube,
  36309. /**
  36310. * Defines the number of radial segments
  36311. */
  36312. radialSegments,
  36313. /**
  36314. * Defines the number of tubular segments
  36315. */
  36316. tubularSegments,
  36317. /**
  36318. * Defines the first number of windings
  36319. */
  36320. p,
  36321. /**
  36322. * Defines the second number of windings
  36323. */
  36324. q, canBeRegenerated, mesh,
  36325. /**
  36326. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36327. */
  36328. side) {
  36329. if (mesh === void 0) { mesh = null; }
  36330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36332. _this.radius = radius;
  36333. _this.tube = tube;
  36334. _this.radialSegments = radialSegments;
  36335. _this.tubularSegments = tubularSegments;
  36336. _this.p = p;
  36337. _this.q = q;
  36338. _this.side = side;
  36339. return _this;
  36340. }
  36341. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36342. 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 });
  36343. };
  36344. TorusKnotGeometry.prototype.copy = function (id) {
  36345. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36346. };
  36347. TorusKnotGeometry.prototype.serialize = function () {
  36348. var serializationObject = _super.prototype.serialize.call(this);
  36349. serializationObject.radius = this.radius;
  36350. serializationObject.tube = this.tube;
  36351. serializationObject.radialSegments = this.radialSegments;
  36352. serializationObject.tubularSegments = this.tubularSegments;
  36353. serializationObject.p = this.p;
  36354. serializationObject.q = this.q;
  36355. return serializationObject;
  36356. };
  36357. ;
  36358. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36359. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36360. return null; // null since geometry could be something else than a ground...
  36361. }
  36362. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36363. if (BABYLON.Tags) {
  36364. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36365. }
  36366. scene.pushGeometry(torusKnot, true);
  36367. return torusKnot;
  36368. };
  36369. return TorusKnotGeometry;
  36370. }(_PrimitiveGeometry));
  36371. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36372. //}
  36373. })(BABYLON || (BABYLON = {}));
  36374. //# sourceMappingURL=babylon.geometry.js.map
  36375. var BABYLON;
  36376. (function (BABYLON) {
  36377. /**
  36378. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36379. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36380. */
  36381. var PostProcessManager = /** @class */ (function () {
  36382. /**
  36383. * Creates a new instance of @see PostProcess
  36384. * @param scene The scene that the post process is associated with.
  36385. */
  36386. function PostProcessManager(scene) {
  36387. this._vertexBuffers = {};
  36388. this._scene = scene;
  36389. }
  36390. PostProcessManager.prototype._prepareBuffers = function () {
  36391. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36392. return;
  36393. }
  36394. // VBO
  36395. var vertices = [];
  36396. vertices.push(1, 1);
  36397. vertices.push(-1, 1);
  36398. vertices.push(-1, -1);
  36399. vertices.push(1, -1);
  36400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36401. this._buildIndexBuffer();
  36402. };
  36403. PostProcessManager.prototype._buildIndexBuffer = function () {
  36404. // Indices
  36405. var indices = [];
  36406. indices.push(0);
  36407. indices.push(1);
  36408. indices.push(2);
  36409. indices.push(0);
  36410. indices.push(2);
  36411. indices.push(3);
  36412. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36413. };
  36414. /**
  36415. * Rebuilds the vertex buffers of the manager.
  36416. */
  36417. PostProcessManager.prototype._rebuild = function () {
  36418. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36419. if (!vb) {
  36420. return;
  36421. }
  36422. vb._rebuild();
  36423. this._buildIndexBuffer();
  36424. };
  36425. // Methods
  36426. /**
  36427. * Prepares a frame to be run through a post process.
  36428. * @param sourceTexture The input texture to the post procesess. (default: null)
  36429. * @param postProcesses An array of post processes to be run. (default: null)
  36430. * @returns True if the post processes were able to be run.
  36431. */
  36432. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36433. if (sourceTexture === void 0) { sourceTexture = null; }
  36434. if (postProcesses === void 0) { postProcesses = null; }
  36435. var camera = this._scene.activeCamera;
  36436. if (!camera) {
  36437. return false;
  36438. }
  36439. var postProcesses = postProcesses || camera._postProcesses;
  36440. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36441. return false;
  36442. }
  36443. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36444. return true;
  36445. };
  36446. /**
  36447. * Manually render a set of post processes to a texture.
  36448. * @param postProcesses An array of post processes to be run.
  36449. * @param targetTexture The target texture to render to.
  36450. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36451. */
  36452. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36453. if (targetTexture === void 0) { targetTexture = null; }
  36454. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36455. var engine = this._scene.getEngine();
  36456. for (var index = 0; index < postProcesses.length; index++) {
  36457. if (index < postProcesses.length - 1) {
  36458. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36459. }
  36460. else {
  36461. if (targetTexture) {
  36462. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36463. }
  36464. else {
  36465. engine.restoreDefaultFramebuffer();
  36466. }
  36467. }
  36468. var pp = postProcesses[index];
  36469. var effect = pp.apply();
  36470. if (effect) {
  36471. pp.onBeforeRenderObservable.notifyObservers(effect);
  36472. // VBOs
  36473. this._prepareBuffers();
  36474. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36475. // Draw order
  36476. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36477. pp.onAfterRenderObservable.notifyObservers(effect);
  36478. }
  36479. }
  36480. // Restore depth buffer
  36481. engine.setDepthBuffer(true);
  36482. engine.setDepthWrite(true);
  36483. };
  36484. /**
  36485. * Finalize the result of the output of the postprocesses.
  36486. * @param doNotPresent If true the result will not be displayed to the screen.
  36487. * @param targetTexture The target texture to render to.
  36488. * @param faceIndex The index of the face to bind the target texture to.
  36489. * @param postProcesses The array of post processes to render.
  36490. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36491. */
  36492. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36493. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36494. var camera = this._scene.activeCamera;
  36495. if (!camera) {
  36496. return;
  36497. }
  36498. postProcesses = postProcesses || camera._postProcesses;
  36499. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36500. return;
  36501. }
  36502. var engine = this._scene.getEngine();
  36503. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36504. if (index < len - 1) {
  36505. postProcesses[index + 1].activate(camera, targetTexture);
  36506. }
  36507. else {
  36508. if (targetTexture) {
  36509. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36510. }
  36511. else {
  36512. engine.restoreDefaultFramebuffer();
  36513. }
  36514. }
  36515. if (doNotPresent) {
  36516. break;
  36517. }
  36518. var pp = postProcesses[index];
  36519. var effect = pp.apply();
  36520. if (effect) {
  36521. pp.onBeforeRenderObservable.notifyObservers(effect);
  36522. // VBOs
  36523. this._prepareBuffers();
  36524. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36525. // Draw order
  36526. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36527. pp.onAfterRenderObservable.notifyObservers(effect);
  36528. }
  36529. }
  36530. // Restore states
  36531. engine.setDepthBuffer(true);
  36532. engine.setDepthWrite(true);
  36533. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36534. };
  36535. /**
  36536. * Disposes of the post process manager.
  36537. */
  36538. PostProcessManager.prototype.dispose = function () {
  36539. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36540. if (buffer) {
  36541. buffer.dispose();
  36542. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36543. }
  36544. if (this._indexBuffer) {
  36545. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36546. this._indexBuffer = null;
  36547. }
  36548. };
  36549. return PostProcessManager;
  36550. }());
  36551. BABYLON.PostProcessManager = PostProcessManager;
  36552. })(BABYLON || (BABYLON = {}));
  36553. //# sourceMappingURL=babylon.postProcessManager.js.map
  36554. var BABYLON;
  36555. (function (BABYLON) {
  36556. /**
  36557. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36558. */
  36559. var PerformanceMonitor = /** @class */ (function () {
  36560. /**
  36561. * constructor
  36562. * @param frameSampleSize The number of samples required to saturate the sliding window
  36563. */
  36564. function PerformanceMonitor(frameSampleSize) {
  36565. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36566. this._enabled = true;
  36567. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36568. }
  36569. /**
  36570. * Samples current frame
  36571. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36572. */
  36573. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36574. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36575. if (!this._enabled)
  36576. return;
  36577. if (this._lastFrameTimeMs != null) {
  36578. var dt = timeMs - this._lastFrameTimeMs;
  36579. this._rollingFrameTime.add(dt);
  36580. }
  36581. this._lastFrameTimeMs = timeMs;
  36582. };
  36583. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36584. /**
  36585. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36586. * @return Average frame time in milliseconds
  36587. */
  36588. get: function () {
  36589. return this._rollingFrameTime.average;
  36590. },
  36591. enumerable: true,
  36592. configurable: true
  36593. });
  36594. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36595. /**
  36596. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36597. * @return Frame time variance in milliseconds squared
  36598. */
  36599. get: function () {
  36600. return this._rollingFrameTime.variance;
  36601. },
  36602. enumerable: true,
  36603. configurable: true
  36604. });
  36605. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36606. /**
  36607. * Returns the frame time of the most recent frame
  36608. * @return Frame time in milliseconds
  36609. */
  36610. get: function () {
  36611. return this._rollingFrameTime.history(0);
  36612. },
  36613. enumerable: true,
  36614. configurable: true
  36615. });
  36616. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36617. /**
  36618. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36619. * @return Framerate in frames per second
  36620. */
  36621. get: function () {
  36622. return 1000.0 / this._rollingFrameTime.average;
  36623. },
  36624. enumerable: true,
  36625. configurable: true
  36626. });
  36627. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36628. /**
  36629. * Returns the average framerate in frames per second using the most recent frame time
  36630. * @return Framerate in frames per second
  36631. */
  36632. get: function () {
  36633. var history = this._rollingFrameTime.history(0);
  36634. if (history === 0) {
  36635. return 0;
  36636. }
  36637. return 1000.0 / history;
  36638. },
  36639. enumerable: true,
  36640. configurable: true
  36641. });
  36642. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36643. /**
  36644. * Returns true if enough samples have been taken to completely fill the sliding window
  36645. * @return true if saturated
  36646. */
  36647. get: function () {
  36648. return this._rollingFrameTime.isSaturated();
  36649. },
  36650. enumerable: true,
  36651. configurable: true
  36652. });
  36653. /**
  36654. * Enables contributions to the sliding window sample set
  36655. */
  36656. PerformanceMonitor.prototype.enable = function () {
  36657. this._enabled = true;
  36658. };
  36659. /**
  36660. * Disables contributions to the sliding window sample set
  36661. * Samples will not be interpolated over the disabled period
  36662. */
  36663. PerformanceMonitor.prototype.disable = function () {
  36664. this._enabled = false;
  36665. //clear last sample to avoid interpolating over the disabled period when next enabled
  36666. this._lastFrameTimeMs = null;
  36667. };
  36668. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36669. /**
  36670. * Returns true if sampling is enabled
  36671. * @return true if enabled
  36672. */
  36673. get: function () {
  36674. return this._enabled;
  36675. },
  36676. enumerable: true,
  36677. configurable: true
  36678. });
  36679. /**
  36680. * Resets performance monitor
  36681. */
  36682. PerformanceMonitor.prototype.reset = function () {
  36683. //clear last sample to avoid interpolating over the disabled period when next enabled
  36684. this._lastFrameTimeMs = null;
  36685. //wipe record
  36686. this._rollingFrameTime.reset();
  36687. };
  36688. return PerformanceMonitor;
  36689. }());
  36690. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36691. /**
  36692. * RollingAverage
  36693. *
  36694. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36695. */
  36696. var RollingAverage = /** @class */ (function () {
  36697. /**
  36698. * constructor
  36699. * @param length The number of samples required to saturate the sliding window
  36700. */
  36701. function RollingAverage(length) {
  36702. this._samples = new Array(length);
  36703. this.reset();
  36704. }
  36705. /**
  36706. * Adds a sample to the sample set
  36707. * @param v The sample value
  36708. */
  36709. RollingAverage.prototype.add = function (v) {
  36710. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36711. var delta;
  36712. //we need to check if we've already wrapped round
  36713. if (this.isSaturated()) {
  36714. //remove bottom of stack from mean
  36715. var bottomValue = this._samples[this._pos];
  36716. delta = bottomValue - this.average;
  36717. this.average -= delta / (this._sampleCount - 1);
  36718. this._m2 -= delta * (bottomValue - this.average);
  36719. }
  36720. else {
  36721. this._sampleCount++;
  36722. }
  36723. //add new value to mean
  36724. delta = v - this.average;
  36725. this.average += delta / (this._sampleCount);
  36726. this._m2 += delta * (v - this.average);
  36727. //set the new variance
  36728. this.variance = this._m2 / (this._sampleCount - 1);
  36729. this._samples[this._pos] = v;
  36730. this._pos++;
  36731. this._pos %= this._samples.length; //positive wrap around
  36732. };
  36733. /**
  36734. * Returns previously added values or null if outside of history or outside the sliding window domain
  36735. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36736. * @return Value previously recorded with add() or null if outside of range
  36737. */
  36738. RollingAverage.prototype.history = function (i) {
  36739. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36740. return 0;
  36741. }
  36742. var i0 = this._wrapPosition(this._pos - 1.0);
  36743. return this._samples[this._wrapPosition(i0 - i)];
  36744. };
  36745. /**
  36746. * Returns true if enough samples have been taken to completely fill the sliding window
  36747. * @return true if sample-set saturated
  36748. */
  36749. RollingAverage.prototype.isSaturated = function () {
  36750. return this._sampleCount >= this._samples.length;
  36751. };
  36752. /**
  36753. * Resets the rolling average (equivalent to 0 samples taken so far)
  36754. */
  36755. RollingAverage.prototype.reset = function () {
  36756. this.average = 0;
  36757. this.variance = 0;
  36758. this._sampleCount = 0;
  36759. this._pos = 0;
  36760. this._m2 = 0;
  36761. };
  36762. /**
  36763. * Wraps a value around the sample range boundaries
  36764. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36765. * @return Wrapped position in sample range
  36766. */
  36767. RollingAverage.prototype._wrapPosition = function (i) {
  36768. var max = this._samples.length;
  36769. return ((i % max) + max) % max;
  36770. };
  36771. return RollingAverage;
  36772. }());
  36773. BABYLON.RollingAverage = RollingAverage;
  36774. })(BABYLON || (BABYLON = {}));
  36775. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36776. var BABYLON;
  36777. (function (BABYLON) {
  36778. /**
  36779. * This groups together the common properties used for image processing either in direct forward pass
  36780. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36781. * or not.
  36782. */
  36783. var ImageProcessingConfiguration = /** @class */ (function () {
  36784. function ImageProcessingConfiguration() {
  36785. /**
  36786. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36787. */
  36788. this.colorCurves = new BABYLON.ColorCurves();
  36789. this._colorCurvesEnabled = false;
  36790. this._colorGradingEnabled = false;
  36791. this._colorGradingWithGreenDepth = true;
  36792. this._colorGradingBGR = true;
  36793. this._exposure = 1.0;
  36794. this._toneMappingEnabled = false;
  36795. this._contrast = 1.0;
  36796. /**
  36797. * Vignette stretch size.
  36798. */
  36799. this.vignetteStretch = 0;
  36800. /**
  36801. * Vignette centre X Offset.
  36802. */
  36803. this.vignetteCentreX = 0;
  36804. /**
  36805. * Vignette centre Y Offset.
  36806. */
  36807. this.vignetteCentreY = 0;
  36808. /**
  36809. * Vignette weight or intensity of the vignette effect.
  36810. */
  36811. this.vignetteWeight = 1.5;
  36812. /**
  36813. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36814. * if vignetteEnabled is set to true.
  36815. */
  36816. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36817. /**
  36818. * Camera field of view used by the Vignette effect.
  36819. */
  36820. this.vignetteCameraFov = 0.5;
  36821. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36822. this._vignetteEnabled = false;
  36823. this._applyByPostProcess = false;
  36824. this._isEnabled = true;
  36825. /**
  36826. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36827. * @type {BABYLON.Observable}
  36828. */
  36829. this.onUpdateParameters = new BABYLON.Observable();
  36830. }
  36831. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36832. /**
  36833. * Gets wether the color curves effect is enabled.
  36834. */
  36835. get: function () {
  36836. return this._colorCurvesEnabled;
  36837. },
  36838. /**
  36839. * Sets wether the color curves effect is enabled.
  36840. */
  36841. set: function (value) {
  36842. if (this._colorCurvesEnabled === value) {
  36843. return;
  36844. }
  36845. this._colorCurvesEnabled = value;
  36846. this._updateParameters();
  36847. },
  36848. enumerable: true,
  36849. configurable: true
  36850. });
  36851. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36852. /**
  36853. * Gets wether the color grading effect is enabled.
  36854. */
  36855. get: function () {
  36856. return this._colorGradingEnabled;
  36857. },
  36858. /**
  36859. * Sets wether the color grading effect is enabled.
  36860. */
  36861. set: function (value) {
  36862. if (this._colorGradingEnabled === value) {
  36863. return;
  36864. }
  36865. this._colorGradingEnabled = value;
  36866. this._updateParameters();
  36867. },
  36868. enumerable: true,
  36869. configurable: true
  36870. });
  36871. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36872. /**
  36873. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36874. */
  36875. get: function () {
  36876. return this._colorGradingWithGreenDepth;
  36877. },
  36878. /**
  36879. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36880. */
  36881. set: function (value) {
  36882. if (this._colorGradingWithGreenDepth === value) {
  36883. return;
  36884. }
  36885. this._colorGradingWithGreenDepth = value;
  36886. this._updateParameters();
  36887. },
  36888. enumerable: true,
  36889. configurable: true
  36890. });
  36891. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36892. /**
  36893. * Gets wether the color grading texture contains BGR values.
  36894. */
  36895. get: function () {
  36896. return this._colorGradingBGR;
  36897. },
  36898. /**
  36899. * Sets wether the color grading texture contains BGR values.
  36900. */
  36901. set: function (value) {
  36902. if (this._colorGradingBGR === value) {
  36903. return;
  36904. }
  36905. this._colorGradingBGR = value;
  36906. this._updateParameters();
  36907. },
  36908. enumerable: true,
  36909. configurable: true
  36910. });
  36911. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36912. /**
  36913. * Gets the Exposure used in the effect.
  36914. */
  36915. get: function () {
  36916. return this._exposure;
  36917. },
  36918. /**
  36919. * Sets the Exposure used in the effect.
  36920. */
  36921. set: function (value) {
  36922. if (this._exposure === value) {
  36923. return;
  36924. }
  36925. this._exposure = value;
  36926. this._updateParameters();
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36932. /**
  36933. * Gets wether the tone mapping effect is enabled.
  36934. */
  36935. get: function () {
  36936. return this._toneMappingEnabled;
  36937. },
  36938. /**
  36939. * Sets wether the tone mapping effect is enabled.
  36940. */
  36941. set: function (value) {
  36942. if (this._toneMappingEnabled === value) {
  36943. return;
  36944. }
  36945. this._toneMappingEnabled = value;
  36946. this._updateParameters();
  36947. },
  36948. enumerable: true,
  36949. configurable: true
  36950. });
  36951. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36952. /**
  36953. * Gets the contrast used in the effect.
  36954. */
  36955. get: function () {
  36956. return this._contrast;
  36957. },
  36958. /**
  36959. * Sets the contrast used in the effect.
  36960. */
  36961. set: function (value) {
  36962. if (this._contrast === value) {
  36963. return;
  36964. }
  36965. this._contrast = value;
  36966. this._updateParameters();
  36967. },
  36968. enumerable: true,
  36969. configurable: true
  36970. });
  36971. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36972. /**
  36973. * Gets the vignette blend mode allowing different kind of effect.
  36974. */
  36975. get: function () {
  36976. return this._vignetteBlendMode;
  36977. },
  36978. /**
  36979. * Sets the vignette blend mode allowing different kind of effect.
  36980. */
  36981. set: function (value) {
  36982. if (this._vignetteBlendMode === value) {
  36983. return;
  36984. }
  36985. this._vignetteBlendMode = value;
  36986. this._updateParameters();
  36987. },
  36988. enumerable: true,
  36989. configurable: true
  36990. });
  36991. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36992. /**
  36993. * Gets wether the vignette effect is enabled.
  36994. */
  36995. get: function () {
  36996. return this._vignetteEnabled;
  36997. },
  36998. /**
  36999. * Sets wether the vignette effect is enabled.
  37000. */
  37001. set: function (value) {
  37002. if (this._vignetteEnabled === value) {
  37003. return;
  37004. }
  37005. this._vignetteEnabled = value;
  37006. this._updateParameters();
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37012. /**
  37013. * Gets wether the image processing is applied through a post process or not.
  37014. */
  37015. get: function () {
  37016. return this._applyByPostProcess;
  37017. },
  37018. /**
  37019. * Sets wether the image processing is applied through a post process or not.
  37020. */
  37021. set: function (value) {
  37022. if (this._applyByPostProcess === value) {
  37023. return;
  37024. }
  37025. this._applyByPostProcess = value;
  37026. this._updateParameters();
  37027. },
  37028. enumerable: true,
  37029. configurable: true
  37030. });
  37031. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37032. /**
  37033. * Gets wether the image processing is enabled or not.
  37034. */
  37035. get: function () {
  37036. return this._isEnabled;
  37037. },
  37038. /**
  37039. * Sets wether the image processing is enabled or not.
  37040. */
  37041. set: function (value) {
  37042. if (this._isEnabled === value) {
  37043. return;
  37044. }
  37045. this._isEnabled = value;
  37046. this._updateParameters();
  37047. },
  37048. enumerable: true,
  37049. configurable: true
  37050. });
  37051. /**
  37052. * Method called each time the image processing information changes requires to recompile the effect.
  37053. */
  37054. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37055. this.onUpdateParameters.notifyObservers(this);
  37056. };
  37057. ImageProcessingConfiguration.prototype.getClassName = function () {
  37058. return "ImageProcessingConfiguration";
  37059. };
  37060. /**
  37061. * Prepare the list of uniforms associated with the Image Processing effects.
  37062. * @param uniformsList The list of uniforms used in the effect
  37063. * @param defines the list of defines currently in use
  37064. */
  37065. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37066. if (defines.EXPOSURE) {
  37067. uniforms.push("exposureLinear");
  37068. }
  37069. if (defines.CONTRAST) {
  37070. uniforms.push("contrast");
  37071. }
  37072. if (defines.COLORGRADING) {
  37073. uniforms.push("colorTransformSettings");
  37074. }
  37075. if (defines.VIGNETTE) {
  37076. uniforms.push("vInverseScreenSize");
  37077. uniforms.push("vignetteSettings1");
  37078. uniforms.push("vignetteSettings2");
  37079. }
  37080. if (defines.COLORCURVES) {
  37081. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37082. }
  37083. };
  37084. /**
  37085. * Prepare the list of samplers associated with the Image Processing effects.
  37086. * @param uniformsList The list of uniforms used in the effect
  37087. * @param defines the list of defines currently in use
  37088. */
  37089. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37090. if (defines.COLORGRADING) {
  37091. samplersList.push("txColorTransform");
  37092. }
  37093. };
  37094. /**
  37095. * Prepare the list of defines associated to the shader.
  37096. * @param defines the list of defines to complete
  37097. */
  37098. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37099. if (forPostProcess === void 0) { forPostProcess = false; }
  37100. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37101. defines.VIGNETTE = false;
  37102. defines.TONEMAPPING = false;
  37103. defines.CONTRAST = false;
  37104. defines.EXPOSURE = false;
  37105. defines.COLORCURVES = false;
  37106. defines.COLORGRADING = false;
  37107. defines.COLORGRADING3D = false;
  37108. defines.IMAGEPROCESSING = false;
  37109. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37110. return;
  37111. }
  37112. defines.VIGNETTE = this.vignetteEnabled;
  37113. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37114. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37115. defines.TONEMAPPING = this.toneMappingEnabled;
  37116. defines.CONTRAST = (this.contrast !== 1.0);
  37117. defines.EXPOSURE = (this.exposure !== 1.0);
  37118. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37119. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37120. if (defines.COLORGRADING) {
  37121. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37122. }
  37123. else {
  37124. defines.COLORGRADING3D = false;
  37125. }
  37126. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37127. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37128. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37129. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37130. };
  37131. /**
  37132. * Returns true if all the image processing information are ready.
  37133. */
  37134. ImageProcessingConfiguration.prototype.isReady = function () {
  37135. // Color Grading texure can not be none blocking.
  37136. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37137. };
  37138. /**
  37139. * Binds the image processing to the shader.
  37140. * @param effect The effect to bind to
  37141. */
  37142. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37143. if (aspectRatio === void 0) { aspectRatio = 1; }
  37144. // Color Curves
  37145. if (this._colorCurvesEnabled && this.colorCurves) {
  37146. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37147. }
  37148. // Vignette
  37149. if (this._vignetteEnabled) {
  37150. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37151. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37152. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37153. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37154. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37155. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37156. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37157. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37158. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37159. var vignettePower = -2.0 * this.vignetteWeight;
  37160. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37161. }
  37162. // Exposure
  37163. effect.setFloat("exposureLinear", this.exposure);
  37164. // Contrast
  37165. effect.setFloat("contrast", this.contrast);
  37166. // Color transform settings
  37167. if (this.colorGradingTexture) {
  37168. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37169. var textureSize = this.colorGradingTexture.getSize().height;
  37170. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37171. 0.5 / textureSize, // textureOffset
  37172. textureSize, // textureSize
  37173. this.colorGradingTexture.level // weight
  37174. );
  37175. }
  37176. };
  37177. /**
  37178. * Clones the current image processing instance.
  37179. * @return The cloned image processing
  37180. */
  37181. ImageProcessingConfiguration.prototype.clone = function () {
  37182. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37183. };
  37184. /**
  37185. * Serializes the current image processing instance to a json representation.
  37186. * @return a JSON representation
  37187. */
  37188. ImageProcessingConfiguration.prototype.serialize = function () {
  37189. return BABYLON.SerializationHelper.Serialize(this);
  37190. };
  37191. /**
  37192. * Parses the image processing from a json representation.
  37193. * @param source the JSON source to parse
  37194. * @return The parsed image processing
  37195. */
  37196. ImageProcessingConfiguration.Parse = function (source) {
  37197. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37198. };
  37199. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37200. /**
  37201. * Used to apply the vignette as a mix with the pixel color.
  37202. */
  37203. get: function () {
  37204. return this._VIGNETTEMODE_MULTIPLY;
  37205. },
  37206. enumerable: true,
  37207. configurable: true
  37208. });
  37209. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37210. /**
  37211. * Used to apply the vignette as a replacement of the pixel color.
  37212. */
  37213. get: function () {
  37214. return this._VIGNETTEMODE_OPAQUE;
  37215. },
  37216. enumerable: true,
  37217. configurable: true
  37218. });
  37219. // Static constants associated to the image processing.
  37220. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37221. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37222. __decorate([
  37223. BABYLON.serializeAsColorCurves()
  37224. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37225. __decorate([
  37226. BABYLON.serialize()
  37227. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37228. __decorate([
  37229. BABYLON.serializeAsTexture()
  37230. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37231. __decorate([
  37232. BABYLON.serialize()
  37233. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37234. __decorate([
  37235. BABYLON.serialize()
  37236. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37237. __decorate([
  37238. BABYLON.serialize()
  37239. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37240. __decorate([
  37241. BABYLON.serialize()
  37242. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37243. __decorate([
  37244. BABYLON.serialize()
  37245. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37246. __decorate([
  37247. BABYLON.serialize()
  37248. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37249. __decorate([
  37250. BABYLON.serialize()
  37251. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37252. __decorate([
  37253. BABYLON.serialize()
  37254. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37255. __decorate([
  37256. BABYLON.serialize()
  37257. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37258. __decorate([
  37259. BABYLON.serialize()
  37260. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37261. __decorate([
  37262. BABYLON.serializeAsColor4()
  37263. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37264. __decorate([
  37265. BABYLON.serialize()
  37266. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37267. __decorate([
  37268. BABYLON.serialize()
  37269. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37270. __decorate([
  37271. BABYLON.serialize()
  37272. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37273. __decorate([
  37274. BABYLON.serialize()
  37275. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37276. __decorate([
  37277. BABYLON.serialize()
  37278. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37279. return ImageProcessingConfiguration;
  37280. }());
  37281. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37282. })(BABYLON || (BABYLON = {}));
  37283. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37284. var BABYLON;
  37285. (function (BABYLON) {
  37286. /**
  37287. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37288. * It can help converting any input color in a desired output one. This can then be used to create effects
  37289. * from sepia, black and white to sixties or futuristic rendering...
  37290. *
  37291. * The only supported format is currently 3dl.
  37292. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37293. */
  37294. var ColorGradingTexture = /** @class */ (function (_super) {
  37295. __extends(ColorGradingTexture, _super);
  37296. /**
  37297. * Instantiates a ColorGradingTexture from the following parameters.
  37298. *
  37299. * @param url The location of the color gradind data (currently only supporting 3dl)
  37300. * @param scene The scene the texture will be used in
  37301. */
  37302. function ColorGradingTexture(url, scene) {
  37303. var _this = _super.call(this, scene) || this;
  37304. if (!url) {
  37305. return _this;
  37306. }
  37307. _this._engine = scene.getEngine();
  37308. _this._textureMatrix = BABYLON.Matrix.Identity();
  37309. _this.name = url;
  37310. _this.url = url;
  37311. _this.hasAlpha = false;
  37312. _this.isCube = false;
  37313. _this.is3D = _this._engine.webGLVersion > 1;
  37314. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37315. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37316. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37317. _this.anisotropicFilteringLevel = 1;
  37318. _this._texture = _this._getFromCache(url, true);
  37319. if (!_this._texture) {
  37320. if (!scene.useDelayedTextureLoading) {
  37321. _this.loadTexture();
  37322. }
  37323. else {
  37324. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37325. }
  37326. }
  37327. return _this;
  37328. }
  37329. /**
  37330. * Returns the texture matrix used in most of the material.
  37331. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37332. */
  37333. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37334. return this._textureMatrix;
  37335. };
  37336. /**
  37337. * Occurs when the file being loaded is a .3dl LUT file.
  37338. */
  37339. ColorGradingTexture.prototype.load3dlTexture = function () {
  37340. var engine = this._engine;
  37341. var texture;
  37342. if (engine.webGLVersion === 1) {
  37343. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37344. }
  37345. else {
  37346. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37347. }
  37348. this._texture = texture;
  37349. var callback = function (text) {
  37350. if (typeof text !== "string") {
  37351. return;
  37352. }
  37353. var data = null;
  37354. var tempData = null;
  37355. var line;
  37356. var lines = text.split('\n');
  37357. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37358. var maxColor = 0;
  37359. for (var i = 0; i < lines.length; i++) {
  37360. line = lines[i];
  37361. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37362. continue;
  37363. if (line.indexOf('#') === 0)
  37364. continue;
  37365. var words = line.split(" ");
  37366. if (size === 0) {
  37367. // Number of space + one
  37368. size = words.length;
  37369. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37370. tempData = new Float32Array(size * size * size * 4);
  37371. continue;
  37372. }
  37373. if (size != 0) {
  37374. var r = Math.max(parseInt(words[0]), 0);
  37375. var g = Math.max(parseInt(words[1]), 0);
  37376. var b = Math.max(parseInt(words[2]), 0);
  37377. maxColor = Math.max(r, maxColor);
  37378. maxColor = Math.max(g, maxColor);
  37379. maxColor = Math.max(b, maxColor);
  37380. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37381. if (tempData) {
  37382. tempData[pixelStorageIndex + 0] = r;
  37383. tempData[pixelStorageIndex + 1] = g;
  37384. tempData[pixelStorageIndex + 2] = b;
  37385. }
  37386. pixelIndexSlice++;
  37387. if (pixelIndexSlice % size == 0) {
  37388. pixelIndexH++;
  37389. pixelIndexSlice = 0;
  37390. if (pixelIndexH % size == 0) {
  37391. pixelIndexW++;
  37392. pixelIndexH = 0;
  37393. }
  37394. }
  37395. }
  37396. }
  37397. if (tempData && data) {
  37398. for (var i = 0; i < tempData.length; i++) {
  37399. if (i > 0 && (i + 1) % 4 === 0) {
  37400. data[i] = 255;
  37401. }
  37402. else {
  37403. var value = tempData[i];
  37404. data[i] = (value / maxColor * 255);
  37405. }
  37406. }
  37407. }
  37408. if (texture.is3D) {
  37409. texture.updateSize(size, size, size);
  37410. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37411. }
  37412. else {
  37413. texture.updateSize(size * size, size);
  37414. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37415. }
  37416. };
  37417. var scene = this.getScene();
  37418. if (scene) {
  37419. scene._loadFile(this.url, callback);
  37420. }
  37421. else {
  37422. this._engine._loadFile(this.url, callback);
  37423. }
  37424. return this._texture;
  37425. };
  37426. /**
  37427. * Starts the loading process of the texture.
  37428. */
  37429. ColorGradingTexture.prototype.loadTexture = function () {
  37430. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37431. this.load3dlTexture();
  37432. }
  37433. };
  37434. /**
  37435. * Clones the color gradind texture.
  37436. */
  37437. ColorGradingTexture.prototype.clone = function () {
  37438. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37439. // Base texture
  37440. newTexture.level = this.level;
  37441. return newTexture;
  37442. };
  37443. /**
  37444. * Called during delayed load for textures.
  37445. */
  37446. ColorGradingTexture.prototype.delayLoad = function () {
  37447. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37448. return;
  37449. }
  37450. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37451. this._texture = this._getFromCache(this.url, true);
  37452. if (!this._texture) {
  37453. this.loadTexture();
  37454. }
  37455. };
  37456. /**
  37457. * Parses a color grading texture serialized by Babylon.
  37458. * @param parsedTexture The texture information being parsedTexture
  37459. * @param scene The scene to load the texture in
  37460. * @param rootUrl The root url of the data assets to load
  37461. * @return A color gradind texture
  37462. */
  37463. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37464. var texture = null;
  37465. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37466. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37467. texture.name = parsedTexture.name;
  37468. texture.level = parsedTexture.level;
  37469. }
  37470. return texture;
  37471. };
  37472. /**
  37473. * Serializes the LUT texture to json format.
  37474. */
  37475. ColorGradingTexture.prototype.serialize = function () {
  37476. if (!this.name) {
  37477. return null;
  37478. }
  37479. var serializationObject = {};
  37480. serializationObject.name = this.name;
  37481. serializationObject.level = this.level;
  37482. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37483. return serializationObject;
  37484. };
  37485. /**
  37486. * Empty line regex stored for GC.
  37487. */
  37488. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37489. return ColorGradingTexture;
  37490. }(BABYLON.BaseTexture));
  37491. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37492. })(BABYLON || (BABYLON = {}));
  37493. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37494. var BABYLON;
  37495. (function (BABYLON) {
  37496. /**
  37497. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37498. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37499. * 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;
  37500. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37501. */
  37502. var ColorCurves = /** @class */ (function () {
  37503. function ColorCurves() {
  37504. this._dirty = true;
  37505. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37506. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37507. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37508. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37509. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37510. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37511. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37512. this._globalHue = 30;
  37513. this._globalDensity = 0;
  37514. this._globalSaturation = 0;
  37515. this._globalExposure = 0;
  37516. this._highlightsHue = 30;
  37517. this._highlightsDensity = 0;
  37518. this._highlightsSaturation = 0;
  37519. this._highlightsExposure = 0;
  37520. this._midtonesHue = 30;
  37521. this._midtonesDensity = 0;
  37522. this._midtonesSaturation = 0;
  37523. this._midtonesExposure = 0;
  37524. this._shadowsHue = 30;
  37525. this._shadowsDensity = 0;
  37526. this._shadowsSaturation = 0;
  37527. this._shadowsExposure = 0;
  37528. }
  37529. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37530. /**
  37531. * Gets the global Hue value.
  37532. * 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).
  37533. */
  37534. get: function () {
  37535. return this._globalHue;
  37536. },
  37537. /**
  37538. * Sets the global Hue value.
  37539. * 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).
  37540. */
  37541. set: function (value) {
  37542. this._globalHue = value;
  37543. this._dirty = true;
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37549. /**
  37550. * Gets the global Density value.
  37551. * 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.
  37552. * Values less than zero provide a filter of opposite hue.
  37553. */
  37554. get: function () {
  37555. return this._globalDensity;
  37556. },
  37557. /**
  37558. * Sets the global Density value.
  37559. * 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.
  37560. * Values less than zero provide a filter of opposite hue.
  37561. */
  37562. set: function (value) {
  37563. this._globalDensity = value;
  37564. this._dirty = true;
  37565. },
  37566. enumerable: true,
  37567. configurable: true
  37568. });
  37569. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37570. /**
  37571. * Gets the global Saturation value.
  37572. * 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.
  37573. */
  37574. get: function () {
  37575. return this._globalSaturation;
  37576. },
  37577. /**
  37578. * Sets the global Saturation value.
  37579. * 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.
  37580. */
  37581. set: function (value) {
  37582. this._globalSaturation = value;
  37583. this._dirty = true;
  37584. },
  37585. enumerable: true,
  37586. configurable: true
  37587. });
  37588. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37589. /**
  37590. * Gets the highlights Hue value.
  37591. * 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).
  37592. */
  37593. get: function () {
  37594. return this._highlightsHue;
  37595. },
  37596. /**
  37597. * Sets the highlights Hue value.
  37598. * 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).
  37599. */
  37600. set: function (value) {
  37601. this._highlightsHue = value;
  37602. this._dirty = true;
  37603. },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37608. /**
  37609. * Gets the highlights Density value.
  37610. * 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.
  37611. * Values less than zero provide a filter of opposite hue.
  37612. */
  37613. get: function () {
  37614. return this._highlightsDensity;
  37615. },
  37616. /**
  37617. * Sets the highlights Density value.
  37618. * 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.
  37619. * Values less than zero provide a filter of opposite hue.
  37620. */
  37621. set: function (value) {
  37622. this._highlightsDensity = value;
  37623. this._dirty = true;
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37629. /**
  37630. * Gets the highlights Saturation value.
  37631. * 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.
  37632. */
  37633. get: function () {
  37634. return this._highlightsSaturation;
  37635. },
  37636. /**
  37637. * Sets the highlights Saturation value.
  37638. * 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.
  37639. */
  37640. set: function (value) {
  37641. this._highlightsSaturation = value;
  37642. this._dirty = true;
  37643. },
  37644. enumerable: true,
  37645. configurable: true
  37646. });
  37647. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37648. /**
  37649. * Gets the highlights Exposure value.
  37650. * 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.
  37651. */
  37652. get: function () {
  37653. return this._highlightsExposure;
  37654. },
  37655. /**
  37656. * Sets the highlights Exposure value.
  37657. * 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.
  37658. */
  37659. set: function (value) {
  37660. this._highlightsExposure = value;
  37661. this._dirty = true;
  37662. },
  37663. enumerable: true,
  37664. configurable: true
  37665. });
  37666. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37667. /**
  37668. * Gets the midtones Hue value.
  37669. * 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).
  37670. */
  37671. get: function () {
  37672. return this._midtonesHue;
  37673. },
  37674. /**
  37675. * Sets the midtones Hue value.
  37676. * 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).
  37677. */
  37678. set: function (value) {
  37679. this._midtonesHue = value;
  37680. this._dirty = true;
  37681. },
  37682. enumerable: true,
  37683. configurable: true
  37684. });
  37685. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37686. /**
  37687. * Gets the midtones Density value.
  37688. * 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.
  37689. * Values less than zero provide a filter of opposite hue.
  37690. */
  37691. get: function () {
  37692. return this._midtonesDensity;
  37693. },
  37694. /**
  37695. * Sets the midtones Density value.
  37696. * 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.
  37697. * Values less than zero provide a filter of opposite hue.
  37698. */
  37699. set: function (value) {
  37700. this._midtonesDensity = value;
  37701. this._dirty = true;
  37702. },
  37703. enumerable: true,
  37704. configurable: true
  37705. });
  37706. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37707. /**
  37708. * Gets the midtones Saturation value.
  37709. * 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.
  37710. */
  37711. get: function () {
  37712. return this._midtonesSaturation;
  37713. },
  37714. /**
  37715. * Sets the midtones Saturation value.
  37716. * 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.
  37717. */
  37718. set: function (value) {
  37719. this._midtonesSaturation = value;
  37720. this._dirty = true;
  37721. },
  37722. enumerable: true,
  37723. configurable: true
  37724. });
  37725. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37726. /**
  37727. * Gets the midtones Exposure value.
  37728. * 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.
  37729. */
  37730. get: function () {
  37731. return this._midtonesExposure;
  37732. },
  37733. /**
  37734. * Sets the midtones Exposure value.
  37735. * 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.
  37736. */
  37737. set: function (value) {
  37738. this._midtonesExposure = value;
  37739. this._dirty = true;
  37740. },
  37741. enumerable: true,
  37742. configurable: true
  37743. });
  37744. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37745. /**
  37746. * Gets the shadows Hue value.
  37747. * 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).
  37748. */
  37749. get: function () {
  37750. return this._shadowsHue;
  37751. },
  37752. /**
  37753. * Sets the shadows Hue value.
  37754. * 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).
  37755. */
  37756. set: function (value) {
  37757. this._shadowsHue = value;
  37758. this._dirty = true;
  37759. },
  37760. enumerable: true,
  37761. configurable: true
  37762. });
  37763. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37764. /**
  37765. * Gets the shadows Density value.
  37766. * 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.
  37767. * Values less than zero provide a filter of opposite hue.
  37768. */
  37769. get: function () {
  37770. return this._shadowsDensity;
  37771. },
  37772. /**
  37773. * Sets the shadows Density value.
  37774. * 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.
  37775. * Values less than zero provide a filter of opposite hue.
  37776. */
  37777. set: function (value) {
  37778. this._shadowsDensity = value;
  37779. this._dirty = true;
  37780. },
  37781. enumerable: true,
  37782. configurable: true
  37783. });
  37784. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37785. /**
  37786. * Gets the shadows Saturation value.
  37787. * 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.
  37788. */
  37789. get: function () {
  37790. return this._shadowsSaturation;
  37791. },
  37792. /**
  37793. * Sets the shadows Saturation value.
  37794. * 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.
  37795. */
  37796. set: function (value) {
  37797. this._shadowsSaturation = value;
  37798. this._dirty = true;
  37799. },
  37800. enumerable: true,
  37801. configurable: true
  37802. });
  37803. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37804. /**
  37805. * Gets the shadows Exposure value.
  37806. * 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.
  37807. */
  37808. get: function () {
  37809. return this._shadowsExposure;
  37810. },
  37811. /**
  37812. * Sets the shadows Exposure value.
  37813. * 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.
  37814. */
  37815. set: function (value) {
  37816. this._shadowsExposure = value;
  37817. this._dirty = true;
  37818. },
  37819. enumerable: true,
  37820. configurable: true
  37821. });
  37822. ColorCurves.prototype.getClassName = function () {
  37823. return "ColorCurves";
  37824. };
  37825. /**
  37826. * Binds the color curves to the shader.
  37827. * @param colorCurves The color curve to bind
  37828. * @param effect The effect to bind to
  37829. */
  37830. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37831. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37832. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37833. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37834. if (colorCurves._dirty) {
  37835. colorCurves._dirty = false;
  37836. // Fill in global info.
  37837. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37838. // Compute highlights info.
  37839. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37840. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37841. // Compute midtones info.
  37842. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37843. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37844. // Compute shadows info.
  37845. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37846. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37847. // Compute deltas (neutral is midtones).
  37848. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37849. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37850. }
  37851. if (effect) {
  37852. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37853. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37854. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37855. }
  37856. };
  37857. /**
  37858. * Prepare the list of uniforms associated with the ColorCurves effects.
  37859. * @param uniformsList The list of uniforms used in the effect
  37860. */
  37861. ColorCurves.PrepareUniforms = function (uniformsList) {
  37862. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37863. };
  37864. /**
  37865. * Returns color grading data based on a hue, density, saturation and exposure value.
  37866. * @param filterHue The hue of the color filter.
  37867. * @param filterDensity The density of the color filter.
  37868. * @param saturation The saturation.
  37869. * @param exposure The exposure.
  37870. * @param result The result data container.
  37871. */
  37872. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37873. if (hue == null) {
  37874. return;
  37875. }
  37876. hue = ColorCurves.clamp(hue, 0, 360);
  37877. density = ColorCurves.clamp(density, -100, 100);
  37878. saturation = ColorCurves.clamp(saturation, -100, 100);
  37879. exposure = ColorCurves.clamp(exposure, -100, 100);
  37880. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37881. // so that the maximum filter density is only 50% control. This provides fine control
  37882. // for small values and reasonable range.
  37883. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37884. density *= 0.5;
  37885. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37886. if (density < 0) {
  37887. density *= -1;
  37888. hue = (hue + 180) % 360;
  37889. }
  37890. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37891. result.scaleToRef(2, result);
  37892. result.a = 1 + 0.01 * saturation;
  37893. };
  37894. /**
  37895. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37896. * @param value The input slider value in range [-100,100].
  37897. * @returns Adjusted value.
  37898. */
  37899. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37900. value /= 100;
  37901. var x = Math.abs(value);
  37902. x = Math.pow(x, 2);
  37903. if (value < 0) {
  37904. x *= -1;
  37905. }
  37906. x *= 100;
  37907. return x;
  37908. };
  37909. /**
  37910. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37911. * @param hue The hue (H) input.
  37912. * @param saturation The saturation (S) input.
  37913. * @param brightness The brightness (B) input.
  37914. * @result An RGBA color represented as Vector4.
  37915. */
  37916. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37917. var h = ColorCurves.clamp(hue, 0, 360);
  37918. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37919. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37920. if (s === 0) {
  37921. result.r = v;
  37922. result.g = v;
  37923. result.b = v;
  37924. }
  37925. else {
  37926. // sector 0 to 5
  37927. h /= 60;
  37928. var i = Math.floor(h);
  37929. // fractional part of h
  37930. var f = h - i;
  37931. var p = v * (1 - s);
  37932. var q = v * (1 - s * f);
  37933. var t = v * (1 - s * (1 - f));
  37934. switch (i) {
  37935. case 0:
  37936. result.r = v;
  37937. result.g = t;
  37938. result.b = p;
  37939. break;
  37940. case 1:
  37941. result.r = q;
  37942. result.g = v;
  37943. result.b = p;
  37944. break;
  37945. case 2:
  37946. result.r = p;
  37947. result.g = v;
  37948. result.b = t;
  37949. break;
  37950. case 3:
  37951. result.r = p;
  37952. result.g = q;
  37953. result.b = v;
  37954. break;
  37955. case 4:
  37956. result.r = t;
  37957. result.g = p;
  37958. result.b = v;
  37959. break;
  37960. default:// case 5:
  37961. result.r = v;
  37962. result.g = p;
  37963. result.b = q;
  37964. break;
  37965. }
  37966. }
  37967. result.a = 1;
  37968. };
  37969. /**
  37970. * Returns a value clamped between min and max
  37971. * @param value The value to clamp
  37972. * @param min The minimum of value
  37973. * @param max The maximum of value
  37974. * @returns The clamped value.
  37975. */
  37976. ColorCurves.clamp = function (value, min, max) {
  37977. return Math.min(Math.max(value, min), max);
  37978. };
  37979. /**
  37980. * Clones the current color curve instance.
  37981. * @return The cloned curves
  37982. */
  37983. ColorCurves.prototype.clone = function () {
  37984. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37985. };
  37986. /**
  37987. * Serializes the current color curve instance to a json representation.
  37988. * @return a JSON representation
  37989. */
  37990. ColorCurves.prototype.serialize = function () {
  37991. return BABYLON.SerializationHelper.Serialize(this);
  37992. };
  37993. /**
  37994. * Parses the color curve from a json representation.
  37995. * @param source the JSON source to parse
  37996. * @return The parsed curves
  37997. */
  37998. ColorCurves.Parse = function (source) {
  37999. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38000. };
  38001. __decorate([
  38002. BABYLON.serialize()
  38003. ], ColorCurves.prototype, "_globalHue", void 0);
  38004. __decorate([
  38005. BABYLON.serialize()
  38006. ], ColorCurves.prototype, "_globalDensity", void 0);
  38007. __decorate([
  38008. BABYLON.serialize()
  38009. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38010. __decorate([
  38011. BABYLON.serialize()
  38012. ], ColorCurves.prototype, "_globalExposure", void 0);
  38013. __decorate([
  38014. BABYLON.serialize()
  38015. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38016. __decorate([
  38017. BABYLON.serialize()
  38018. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38019. __decorate([
  38020. BABYLON.serialize()
  38021. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38022. __decorate([
  38023. BABYLON.serialize()
  38024. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38025. __decorate([
  38026. BABYLON.serialize()
  38027. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38028. __decorate([
  38029. BABYLON.serialize()
  38030. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38031. __decorate([
  38032. BABYLON.serialize()
  38033. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38034. __decorate([
  38035. BABYLON.serialize()
  38036. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38037. return ColorCurves;
  38038. }());
  38039. BABYLON.ColorCurves = ColorCurves;
  38040. })(BABYLON || (BABYLON = {}));
  38041. //# sourceMappingURL=babylon.colorCurves.js.map
  38042. //# sourceMappingURL=babylon.behavior.js.map
  38043. var BABYLON;
  38044. (function (BABYLON) {
  38045. /**
  38046. * "Static Class" containing the most commonly used helper while dealing with material for
  38047. * rendering purpose.
  38048. *
  38049. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38050. *
  38051. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38052. */
  38053. var MaterialHelper = /** @class */ (function () {
  38054. function MaterialHelper() {
  38055. }
  38056. /**
  38057. * Bind the current view position to an effect.
  38058. * @param effect The effect to be bound
  38059. * @param scene The scene the eyes position is used from
  38060. */
  38061. MaterialHelper.BindEyePosition = function (effect, scene) {
  38062. if (scene._forcedViewPosition) {
  38063. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38064. return;
  38065. }
  38066. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38067. };
  38068. /**
  38069. * Helps preparing the defines values about the UVs in used in the effect.
  38070. * UVs are shared as much as we can accross chanels in the shaders.
  38071. * @param texture The texture we are preparing the UVs for
  38072. * @param defines The defines to update
  38073. * @param key The chanel key "diffuse", "specular"... used in the shader
  38074. */
  38075. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38076. defines._needUVs = true;
  38077. defines[key] = true;
  38078. if (texture.getTextureMatrix().isIdentity(true)) {
  38079. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38080. if (texture.coordinatesIndex === 0) {
  38081. defines["MAINUV1"] = true;
  38082. }
  38083. else {
  38084. defines["MAINUV2"] = true;
  38085. }
  38086. }
  38087. else {
  38088. defines[key + "DIRECTUV"] = 0;
  38089. }
  38090. };
  38091. /**
  38092. * Binds a texture matrix value to its corrsponding uniform
  38093. * @param texture The texture to bind the matrix for
  38094. * @param uniformBuffer The uniform buffer receivin the data
  38095. * @param key The chanel key "diffuse", "specular"... used in the shader
  38096. */
  38097. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38098. var matrix = texture.getTextureMatrix();
  38099. if (!matrix.isIdentity(true)) {
  38100. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38101. }
  38102. };
  38103. /**
  38104. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38105. * @param mesh defines the current mesh
  38106. * @param scene defines the current scene
  38107. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38108. * @param pointsCloud defines if point cloud rendering has to be turned on
  38109. * @param fogEnabled defines if fog has to be turned on
  38110. * @param alphaTest defines if alpha testing has to be turned on
  38111. * @param defines defines the current list of defines
  38112. */
  38113. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38114. if (defines._areMiscDirty) {
  38115. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38116. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38117. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38118. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38119. defines["ALPHATEST"] = alphaTest;
  38120. }
  38121. };
  38122. /**
  38123. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38124. * @param scene defines the current scene
  38125. * @param engine defines the current engine
  38126. * @param defines specifies the list of active defines
  38127. * @param useInstances defines if instances have to be turned on
  38128. * @param useClipPlane defines if clip plane have to be turned on
  38129. */
  38130. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38131. if (useClipPlane === void 0) { useClipPlane = null; }
  38132. var changed = false;
  38133. if (useClipPlane == null) {
  38134. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38135. }
  38136. if (defines["CLIPPLANE"] !== useClipPlane) {
  38137. defines["CLIPPLANE"] = useClipPlane;
  38138. changed = true;
  38139. }
  38140. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38141. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38142. changed = true;
  38143. }
  38144. if (defines["INSTANCES"] !== useInstances) {
  38145. defines["INSTANCES"] = useInstances;
  38146. changed = true;
  38147. }
  38148. if (changed) {
  38149. defines.markAsUnprocessed();
  38150. }
  38151. };
  38152. /**
  38153. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38154. * @param mesh The mesh containing the geometry data we will draw
  38155. * @param defines The defines to update
  38156. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38157. * @param useBones Precise whether bones should be used or not (override mesh info)
  38158. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38159. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38160. * @returns false if defines are considered not dirty and have not been checked
  38161. */
  38162. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38163. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38164. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38165. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38166. return false;
  38167. }
  38168. defines._normals = defines._needNormals;
  38169. defines._uvs = defines._needUVs;
  38170. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38171. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38172. defines["TANGENT"] = true;
  38173. }
  38174. if (defines._needUVs) {
  38175. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38176. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38177. }
  38178. else {
  38179. defines["UV1"] = false;
  38180. defines["UV2"] = false;
  38181. }
  38182. if (useVertexColor) {
  38183. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38184. defines["VERTEXCOLOR"] = hasVertexColors;
  38185. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38186. }
  38187. if (useBones) {
  38188. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38189. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38190. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38191. }
  38192. else {
  38193. defines["NUM_BONE_INFLUENCERS"] = 0;
  38194. defines["BonesPerMesh"] = 0;
  38195. }
  38196. }
  38197. if (useMorphTargets) {
  38198. var manager = mesh.morphTargetManager;
  38199. if (manager) {
  38200. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38201. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38202. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38203. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38204. }
  38205. else {
  38206. defines["MORPHTARGETS_TANGENT"] = false;
  38207. defines["MORPHTARGETS_NORMAL"] = false;
  38208. defines["MORPHTARGETS"] = false;
  38209. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38210. }
  38211. }
  38212. return true;
  38213. };
  38214. /**
  38215. * Prepares the defines related to the light information passed in parameter
  38216. * @param scene The scene we are intending to draw
  38217. * @param mesh The mesh the effect is compiling for
  38218. * @param defines The defines to update
  38219. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38220. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38221. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38222. * @returns true if normals will be required for the rest of the effect
  38223. */
  38224. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38225. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38226. if (disableLighting === void 0) { disableLighting = false; }
  38227. if (!defines._areLightsDirty) {
  38228. return defines._needNormals;
  38229. }
  38230. var lightIndex = 0;
  38231. var needNormals = false;
  38232. var needRebuild = false;
  38233. var lightmapMode = false;
  38234. var shadowEnabled = false;
  38235. var specularEnabled = false;
  38236. if (scene.lightsEnabled && !disableLighting) {
  38237. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38238. var light = _a[_i];
  38239. needNormals = true;
  38240. if (defines["LIGHT" + lightIndex] === undefined) {
  38241. needRebuild = true;
  38242. }
  38243. defines["LIGHT" + lightIndex] = true;
  38244. defines["SPOTLIGHT" + lightIndex] = false;
  38245. defines["HEMILIGHT" + lightIndex] = false;
  38246. defines["POINTLIGHT" + lightIndex] = false;
  38247. defines["DIRLIGHT" + lightIndex] = false;
  38248. var type;
  38249. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38250. type = "SPOTLIGHT" + lightIndex;
  38251. var spotLight = light;
  38252. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38253. }
  38254. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38255. type = "HEMILIGHT" + lightIndex;
  38256. }
  38257. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38258. type = "POINTLIGHT" + lightIndex;
  38259. }
  38260. else {
  38261. type = "DIRLIGHT" + lightIndex;
  38262. }
  38263. defines[type] = true;
  38264. // Specular
  38265. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38266. specularEnabled = true;
  38267. }
  38268. // Shadows
  38269. defines["SHADOW" + lightIndex] = false;
  38270. defines["SHADOWPCF" + lightIndex] = false;
  38271. defines["SHADOWESM" + lightIndex] = false;
  38272. defines["SHADOWCUBE" + lightIndex] = false;
  38273. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38274. var shadowGenerator = light.getShadowGenerator();
  38275. if (shadowGenerator) {
  38276. shadowEnabled = true;
  38277. shadowGenerator.prepareDefines(defines, lightIndex);
  38278. }
  38279. }
  38280. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38281. lightmapMode = true;
  38282. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38283. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38284. }
  38285. else {
  38286. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38287. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38288. }
  38289. lightIndex++;
  38290. if (lightIndex === maxSimultaneousLights)
  38291. break;
  38292. }
  38293. }
  38294. defines["SPECULARTERM"] = specularEnabled;
  38295. defines["SHADOWS"] = shadowEnabled;
  38296. // Resetting all other lights if any
  38297. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38298. if (defines["LIGHT" + index] !== undefined) {
  38299. defines["LIGHT" + index] = false;
  38300. defines["HEMILIGHT" + lightIndex] = false;
  38301. defines["POINTLIGHT" + lightIndex] = false;
  38302. defines["DIRLIGHT" + lightIndex] = false;
  38303. defines["SPOTLIGHT" + lightIndex] = false;
  38304. defines["SHADOW" + lightIndex] = false;
  38305. }
  38306. }
  38307. var caps = scene.getEngine().getCaps();
  38308. if (defines["SHADOWFLOAT"] === undefined) {
  38309. needRebuild = true;
  38310. }
  38311. defines["SHADOWFLOAT"] = shadowEnabled &&
  38312. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38313. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38314. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38315. if (needRebuild) {
  38316. defines.rebuild();
  38317. }
  38318. return needNormals;
  38319. };
  38320. /**
  38321. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38322. * that won t be acctive due to defines being turned off.
  38323. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38324. * @param samplersList The samplers list
  38325. * @param defines The defines helping in the list generation
  38326. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38327. */
  38328. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38329. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38330. var uniformsList;
  38331. var uniformBuffersList = null;
  38332. if (uniformsListOrOptions.uniformsNames) {
  38333. var options = uniformsListOrOptions;
  38334. uniformsList = options.uniformsNames;
  38335. uniformBuffersList = options.uniformBuffersNames;
  38336. samplersList = options.samplers;
  38337. defines = options.defines;
  38338. maxSimultaneousLights = options.maxSimultaneousLights;
  38339. }
  38340. else {
  38341. uniformsList = uniformsListOrOptions;
  38342. if (!samplersList) {
  38343. samplersList = [];
  38344. }
  38345. }
  38346. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38347. if (!defines["LIGHT" + lightIndex]) {
  38348. break;
  38349. }
  38350. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38351. if (uniformBuffersList) {
  38352. uniformBuffersList.push("Light" + lightIndex);
  38353. }
  38354. samplersList.push("shadowSampler" + lightIndex);
  38355. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38356. samplersList.push("projectionLightSampler" + lightIndex);
  38357. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38358. }
  38359. }
  38360. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38361. uniformsList.push("morphTargetInfluences");
  38362. }
  38363. };
  38364. /**
  38365. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38366. * @param defines The defines to update while falling back
  38367. * @param fallbacks The authorized effect fallbacks
  38368. * @param maxSimultaneousLights The maximum number of lights allowed
  38369. * @param rank the current rank of the Effect
  38370. * @returns The newly affected rank
  38371. */
  38372. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38373. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38374. if (rank === void 0) { rank = 0; }
  38375. var lightFallbackRank = 0;
  38376. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38377. if (!defines["LIGHT" + lightIndex]) {
  38378. break;
  38379. }
  38380. if (lightIndex > 0) {
  38381. lightFallbackRank = rank + lightIndex;
  38382. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38383. }
  38384. if (!defines["SHADOWS"]) {
  38385. if (defines["SHADOW" + lightIndex]) {
  38386. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38387. }
  38388. if (defines["SHADOWPCF" + lightIndex]) {
  38389. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38390. }
  38391. if (defines["SHADOWESM" + lightIndex]) {
  38392. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38393. }
  38394. }
  38395. }
  38396. return lightFallbackRank++;
  38397. };
  38398. /**
  38399. * Prepares the list of attributes required for morph targets according to the effect defines.
  38400. * @param attribs The current list of supported attribs
  38401. * @param mesh The mesh to prepare the morph targets attributes for
  38402. * @param defines The current Defines of the effect
  38403. */
  38404. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38405. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38406. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38407. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38408. var manager = mesh.morphTargetManager;
  38409. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38410. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38411. for (var index = 0; index < influencers; index++) {
  38412. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38413. if (normal) {
  38414. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38415. }
  38416. if (tangent) {
  38417. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38418. }
  38419. if (attribs.length > maxAttributesCount) {
  38420. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38421. }
  38422. }
  38423. }
  38424. };
  38425. /**
  38426. * Prepares the list of attributes required for bones according to the effect defines.
  38427. * @param attribs The current list of supported attribs
  38428. * @param mesh The mesh to prepare the bones attributes for
  38429. * @param defines The current Defines of the effect
  38430. * @param fallbacks The current efffect fallback strategy
  38431. */
  38432. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38433. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38434. fallbacks.addCPUSkinningFallback(0, mesh);
  38435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38437. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38438. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38439. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38440. }
  38441. }
  38442. };
  38443. /**
  38444. * Prepares the list of attributes required for instances according to the effect defines.
  38445. * @param attribs The current list of supported attribs
  38446. * @param defines The current Defines of the effect
  38447. */
  38448. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38449. if (defines["INSTANCES"]) {
  38450. attribs.push("world0");
  38451. attribs.push("world1");
  38452. attribs.push("world2");
  38453. attribs.push("world3");
  38454. }
  38455. };
  38456. /**
  38457. * Binds the light shadow information to the effect for the given mesh.
  38458. * @param light The light containing the generator
  38459. * @param scene The scene the lights belongs to
  38460. * @param mesh The mesh we are binding the information to render
  38461. * @param lightIndex The light index in the effect used to render the mesh
  38462. * @param effect The effect we are binding the data to
  38463. */
  38464. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38465. if (light.shadowEnabled && mesh.receiveShadows) {
  38466. var shadowGenerator = light.getShadowGenerator();
  38467. if (shadowGenerator) {
  38468. shadowGenerator.bindShadowLight(lightIndex, effect);
  38469. }
  38470. }
  38471. };
  38472. /**
  38473. * Binds the light information to the effect.
  38474. * @param light The light containing the generator
  38475. * @param effect The effect we are binding the data to
  38476. * @param lightIndex The light index in the effect used to render
  38477. */
  38478. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38479. light.transferToEffect(effect, lightIndex + "");
  38480. };
  38481. /**
  38482. * Binds the lights information from the scene to the effect for the given mesh.
  38483. * @param scene The scene the lights belongs to
  38484. * @param mesh The mesh we are binding the information to render
  38485. * @param effect The effect we are binding the data to
  38486. * @param defines The generated defines for the effect
  38487. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38488. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38489. */
  38490. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38491. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38492. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38493. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38494. for (var i = 0; i < len; i++) {
  38495. var light = mesh._lightSources[i];
  38496. var iAsString = i.toString();
  38497. var scaledIntensity = light.getScaledIntensity();
  38498. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38499. MaterialHelper.BindLightProperties(light, effect, i);
  38500. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38501. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38502. if (defines["SPECULARTERM"]) {
  38503. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38504. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38505. }
  38506. // Shadows
  38507. if (scene.shadowsEnabled) {
  38508. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38509. }
  38510. light._uniformBuffer.update();
  38511. }
  38512. };
  38513. /**
  38514. * Binds the fog information from the scene to the effect for the given mesh.
  38515. * @param scene The scene the lights belongs to
  38516. * @param mesh The mesh we are binding the information to render
  38517. * @param effect The effect we are binding the data to
  38518. */
  38519. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38520. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38521. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38522. effect.setColor3("vFogColor", scene.fogColor);
  38523. }
  38524. };
  38525. /**
  38526. * Binds the bones information from the mesh to the effect.
  38527. * @param mesh The mesh we are binding the information to render
  38528. * @param effect The effect we are binding the data to
  38529. */
  38530. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38531. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38532. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38533. if (matrices && effect) {
  38534. effect.setMatrices("mBones", matrices);
  38535. }
  38536. }
  38537. };
  38538. /**
  38539. * Binds the morph targets information from the mesh to the effect.
  38540. * @param abstractMesh The mesh we are binding the information to render
  38541. * @param effect The effect we are binding the data to
  38542. */
  38543. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38544. var manager = abstractMesh.morphTargetManager;
  38545. if (!abstractMesh || !manager) {
  38546. return;
  38547. }
  38548. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38549. };
  38550. /**
  38551. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38552. * @param defines The generated defines used in the effect
  38553. * @param effect The effect we are binding the data to
  38554. * @param scene The scene we are willing to render with logarithmic scale for
  38555. */
  38556. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38557. if (defines["LOGARITHMICDEPTH"]) {
  38558. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38559. }
  38560. };
  38561. /**
  38562. * Binds the clip plane information from the scene to the effect.
  38563. * @param scene The scene the clip plane information are extracted from
  38564. * @param effect The effect we are binding the data to
  38565. */
  38566. MaterialHelper.BindClipPlane = function (effect, scene) {
  38567. if (scene.clipPlane) {
  38568. var clipPlane = scene.clipPlane;
  38569. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38570. }
  38571. };
  38572. return MaterialHelper;
  38573. }());
  38574. BABYLON.MaterialHelper = MaterialHelper;
  38575. })(BABYLON || (BABYLON = {}));
  38576. //# sourceMappingURL=babylon.materialHelper.js.map
  38577. var BABYLON;
  38578. (function (BABYLON) {
  38579. var PushMaterial = /** @class */ (function (_super) {
  38580. __extends(PushMaterial, _super);
  38581. function PushMaterial(name, scene) {
  38582. var _this = _super.call(this, name, scene) || this;
  38583. _this._normalMatrix = new BABYLON.Matrix();
  38584. _this.storeEffectOnSubMeshes = true;
  38585. return _this;
  38586. }
  38587. PushMaterial.prototype.getEffect = function () {
  38588. return this._activeEffect;
  38589. };
  38590. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38591. if (!mesh) {
  38592. return false;
  38593. }
  38594. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38595. return true;
  38596. }
  38597. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38598. };
  38599. /**
  38600. * Binds the given world matrix to the active effect
  38601. *
  38602. * @param world the matrix to bind
  38603. */
  38604. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38605. this._activeEffect.setMatrix("world", world);
  38606. };
  38607. /**
  38608. * Binds the given normal matrix to the active effect
  38609. *
  38610. * @param normalMatrix the matrix to bind
  38611. */
  38612. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38613. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38614. };
  38615. PushMaterial.prototype.bind = function (world, mesh) {
  38616. if (!mesh) {
  38617. return;
  38618. }
  38619. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38620. };
  38621. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38622. if (effect === void 0) { effect = null; }
  38623. _super.prototype._afterBind.call(this, mesh);
  38624. this.getScene()._cachedEffect = effect;
  38625. };
  38626. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38627. if (visibility === void 0) { visibility = 1; }
  38628. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38629. };
  38630. return PushMaterial;
  38631. }(BABYLON.Material));
  38632. BABYLON.PushMaterial = PushMaterial;
  38633. })(BABYLON || (BABYLON = {}));
  38634. //# sourceMappingURL=babylon.pushMaterial.js.map
  38635. var BABYLON;
  38636. (function (BABYLON) {
  38637. /** @ignore */
  38638. var StandardMaterialDefines = /** @class */ (function (_super) {
  38639. __extends(StandardMaterialDefines, _super);
  38640. function StandardMaterialDefines() {
  38641. var _this = _super.call(this) || this;
  38642. _this.MAINUV1 = false;
  38643. _this.MAINUV2 = false;
  38644. _this.DIFFUSE = false;
  38645. _this.DIFFUSEDIRECTUV = 0;
  38646. _this.AMBIENT = false;
  38647. _this.AMBIENTDIRECTUV = 0;
  38648. _this.OPACITY = false;
  38649. _this.OPACITYDIRECTUV = 0;
  38650. _this.OPACITYRGB = false;
  38651. _this.REFLECTION = false;
  38652. _this.EMISSIVE = false;
  38653. _this.EMISSIVEDIRECTUV = 0;
  38654. _this.SPECULAR = false;
  38655. _this.SPECULARDIRECTUV = 0;
  38656. _this.BUMP = false;
  38657. _this.BUMPDIRECTUV = 0;
  38658. _this.PARALLAX = false;
  38659. _this.PARALLAXOCCLUSION = false;
  38660. _this.SPECULAROVERALPHA = false;
  38661. _this.CLIPPLANE = false;
  38662. _this.ALPHATEST = false;
  38663. _this.DEPTHPREPASS = false;
  38664. _this.ALPHAFROMDIFFUSE = false;
  38665. _this.POINTSIZE = false;
  38666. _this.FOG = false;
  38667. _this.SPECULARTERM = false;
  38668. _this.DIFFUSEFRESNEL = false;
  38669. _this.OPACITYFRESNEL = false;
  38670. _this.REFLECTIONFRESNEL = false;
  38671. _this.REFRACTIONFRESNEL = false;
  38672. _this.EMISSIVEFRESNEL = false;
  38673. _this.FRESNEL = false;
  38674. _this.NORMAL = false;
  38675. _this.UV1 = false;
  38676. _this.UV2 = false;
  38677. _this.VERTEXCOLOR = false;
  38678. _this.VERTEXALPHA = false;
  38679. _this.NUM_BONE_INFLUENCERS = 0;
  38680. _this.BonesPerMesh = 0;
  38681. _this.INSTANCES = false;
  38682. _this.GLOSSINESS = false;
  38683. _this.ROUGHNESS = false;
  38684. _this.EMISSIVEASILLUMINATION = false;
  38685. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38686. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38687. _this.LIGHTMAP = false;
  38688. _this.LIGHTMAPDIRECTUV = 0;
  38689. _this.OBJECTSPACE_NORMALMAP = false;
  38690. _this.USELIGHTMAPASSHADOWMAP = false;
  38691. _this.REFLECTIONMAP_3D = false;
  38692. _this.REFLECTIONMAP_SPHERICAL = false;
  38693. _this.REFLECTIONMAP_PLANAR = false;
  38694. _this.REFLECTIONMAP_CUBIC = false;
  38695. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38696. _this.REFLECTIONMAP_PROJECTION = false;
  38697. _this.REFLECTIONMAP_SKYBOX = false;
  38698. _this.REFLECTIONMAP_EXPLICIT = false;
  38699. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38700. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38701. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38702. _this.INVERTCUBICMAP = false;
  38703. _this.LOGARITHMICDEPTH = false;
  38704. _this.REFRACTION = false;
  38705. _this.REFRACTIONMAP_3D = false;
  38706. _this.REFLECTIONOVERALPHA = false;
  38707. _this.TWOSIDEDLIGHTING = false;
  38708. _this.SHADOWFLOAT = false;
  38709. _this.MORPHTARGETS = false;
  38710. _this.MORPHTARGETS_NORMAL = false;
  38711. _this.MORPHTARGETS_TANGENT = false;
  38712. _this.NUM_MORPH_INFLUENCERS = 0;
  38713. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38714. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38715. _this.IMAGEPROCESSING = false;
  38716. _this.VIGNETTE = false;
  38717. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38718. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38719. _this.TONEMAPPING = false;
  38720. _this.CONTRAST = false;
  38721. _this.COLORCURVES = false;
  38722. _this.COLORGRADING = false;
  38723. _this.COLORGRADING3D = false;
  38724. _this.SAMPLER3DGREENDEPTH = false;
  38725. _this.SAMPLER3DBGRMAP = false;
  38726. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38727. _this.EXPOSURE = false;
  38728. _this.rebuild();
  38729. return _this;
  38730. }
  38731. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38732. var modes = [
  38733. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38734. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38735. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38736. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38737. ];
  38738. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38739. var mode = modes_1[_i];
  38740. this[mode] = (mode === modeToEnable);
  38741. }
  38742. };
  38743. return StandardMaterialDefines;
  38744. }(BABYLON.MaterialDefines));
  38745. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38746. var StandardMaterial = /** @class */ (function (_super) {
  38747. __extends(StandardMaterial, _super);
  38748. function StandardMaterial(name, scene) {
  38749. var _this = _super.call(this, name, scene) || this;
  38750. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38751. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38752. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38753. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38754. _this.specularPower = 64;
  38755. _this._useAlphaFromDiffuseTexture = false;
  38756. _this._useEmissiveAsIllumination = false;
  38757. _this._linkEmissiveWithDiffuse = false;
  38758. _this._useSpecularOverAlpha = false;
  38759. _this._useReflectionOverAlpha = false;
  38760. _this._disableLighting = false;
  38761. _this._useObjectSpaceNormalMap = false;
  38762. _this._useParallax = false;
  38763. _this._useParallaxOcclusion = false;
  38764. _this.parallaxScaleBias = 0.05;
  38765. _this._roughness = 0;
  38766. _this.indexOfRefraction = 0.98;
  38767. _this.invertRefractionY = true;
  38768. _this._useLightmapAsShadowmap = false;
  38769. _this._useReflectionFresnelFromSpecular = false;
  38770. _this._useGlossinessFromSpecularMapAlpha = false;
  38771. _this._maxSimultaneousLights = 4;
  38772. /**
  38773. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38774. */
  38775. _this._invertNormalMapX = false;
  38776. /**
  38777. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38778. */
  38779. _this._invertNormalMapY = false;
  38780. /**
  38781. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38782. */
  38783. _this._twoSidedLighting = false;
  38784. _this._renderTargets = new BABYLON.SmartArray(16);
  38785. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38786. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38787. // Setup the default processing configuration to the scene.
  38788. _this._attachImageProcessingConfiguration(null);
  38789. _this.getRenderTargetTextures = function () {
  38790. _this._renderTargets.reset();
  38791. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38792. _this._renderTargets.push(_this._reflectionTexture);
  38793. }
  38794. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38795. _this._renderTargets.push(_this._refractionTexture);
  38796. }
  38797. return _this._renderTargets;
  38798. };
  38799. return _this;
  38800. }
  38801. ;
  38802. ;
  38803. ;
  38804. ;
  38805. ;
  38806. ;
  38807. ;
  38808. ;
  38809. ;
  38810. ;
  38811. ;
  38812. ;
  38813. ;
  38814. ;
  38815. ;
  38816. ;
  38817. ;
  38818. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38819. /**
  38820. * Gets the image processing configuration used either in this material.
  38821. */
  38822. get: function () {
  38823. return this._imageProcessingConfiguration;
  38824. },
  38825. /**
  38826. * Sets the Default image processing configuration used either in the this material.
  38827. *
  38828. * If sets to null, the scene one is in use.
  38829. */
  38830. set: function (value) {
  38831. this._attachImageProcessingConfiguration(value);
  38832. // Ensure the effect will be rebuilt.
  38833. this._markAllSubMeshesAsTexturesDirty();
  38834. },
  38835. enumerable: true,
  38836. configurable: true
  38837. });
  38838. /**
  38839. * Attaches a new image processing configuration to the Standard Material.
  38840. * @param configuration
  38841. */
  38842. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38843. var _this = this;
  38844. if (configuration === this._imageProcessingConfiguration) {
  38845. return;
  38846. }
  38847. // Detaches observer.
  38848. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38849. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38850. }
  38851. // Pick the scene configuration if needed.
  38852. if (!configuration) {
  38853. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38854. }
  38855. else {
  38856. this._imageProcessingConfiguration = configuration;
  38857. }
  38858. // Attaches observer.
  38859. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38860. _this._markAllSubMeshesAsImageProcessingDirty();
  38861. });
  38862. };
  38863. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38864. /**
  38865. * Gets wether the color curves effect is enabled.
  38866. */
  38867. get: function () {
  38868. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38869. },
  38870. /**
  38871. * Sets wether the color curves effect is enabled.
  38872. */
  38873. set: function (value) {
  38874. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38875. },
  38876. enumerable: true,
  38877. configurable: true
  38878. });
  38879. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38880. /**
  38881. * Gets wether the color grading effect is enabled.
  38882. */
  38883. get: function () {
  38884. return this.imageProcessingConfiguration.colorGradingEnabled;
  38885. },
  38886. /**
  38887. * Gets wether the color grading effect is enabled.
  38888. */
  38889. set: function (value) {
  38890. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38896. /**
  38897. * Gets wether tonemapping is enabled or not.
  38898. */
  38899. get: function () {
  38900. return this._imageProcessingConfiguration.toneMappingEnabled;
  38901. },
  38902. /**
  38903. * Sets wether tonemapping is enabled or not
  38904. */
  38905. set: function (value) {
  38906. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38907. },
  38908. enumerable: true,
  38909. configurable: true
  38910. });
  38911. ;
  38912. ;
  38913. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38914. /**
  38915. * The camera exposure used on this material.
  38916. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38917. * This corresponds to a photographic exposure.
  38918. */
  38919. get: function () {
  38920. return this._imageProcessingConfiguration.exposure;
  38921. },
  38922. /**
  38923. * The camera exposure used on this material.
  38924. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38925. * This corresponds to a photographic exposure.
  38926. */
  38927. set: function (value) {
  38928. this._imageProcessingConfiguration.exposure = value;
  38929. },
  38930. enumerable: true,
  38931. configurable: true
  38932. });
  38933. ;
  38934. ;
  38935. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38936. /**
  38937. * Gets The camera contrast used on this material.
  38938. */
  38939. get: function () {
  38940. return this._imageProcessingConfiguration.contrast;
  38941. },
  38942. /**
  38943. * Sets The camera contrast used on this material.
  38944. */
  38945. set: function (value) {
  38946. this._imageProcessingConfiguration.contrast = value;
  38947. },
  38948. enumerable: true,
  38949. configurable: true
  38950. });
  38951. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38952. /**
  38953. * Gets the Color Grading 2D Lookup Texture.
  38954. */
  38955. get: function () {
  38956. return this._imageProcessingConfiguration.colorGradingTexture;
  38957. },
  38958. /**
  38959. * Sets the Color Grading 2D Lookup Texture.
  38960. */
  38961. set: function (value) {
  38962. this._imageProcessingConfiguration.colorGradingTexture = value;
  38963. },
  38964. enumerable: true,
  38965. configurable: true
  38966. });
  38967. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38968. /**
  38969. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38970. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38971. * 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;
  38972. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38973. */
  38974. get: function () {
  38975. return this._imageProcessingConfiguration.colorCurves;
  38976. },
  38977. /**
  38978. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38979. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38980. * 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;
  38981. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38982. */
  38983. set: function (value) {
  38984. this._imageProcessingConfiguration.colorCurves = value;
  38985. },
  38986. enumerable: true,
  38987. configurable: true
  38988. });
  38989. StandardMaterial.prototype.getClassName = function () {
  38990. return "StandardMaterial";
  38991. };
  38992. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38993. get: function () {
  38994. return this._useLogarithmicDepth;
  38995. },
  38996. set: function (value) {
  38997. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38998. this._markAllSubMeshesAsMiscDirty();
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. StandardMaterial.prototype.needAlphaBlending = function () {
  39004. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39005. };
  39006. StandardMaterial.prototype.needAlphaTesting = function () {
  39007. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39008. };
  39009. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39010. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39011. };
  39012. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39013. return this._diffuseTexture;
  39014. };
  39015. /**
  39016. * Child classes can use it to update shaders
  39017. */
  39018. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39019. if (useInstances === void 0) { useInstances = false; }
  39020. if (subMesh.effect && this.isFrozen) {
  39021. if (this._wasPreviouslyReady && subMesh.effect) {
  39022. return true;
  39023. }
  39024. }
  39025. if (!subMesh._materialDefines) {
  39026. subMesh._materialDefines = new StandardMaterialDefines();
  39027. }
  39028. var scene = this.getScene();
  39029. var defines = subMesh._materialDefines;
  39030. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39031. if (defines._renderId === scene.getRenderId()) {
  39032. return true;
  39033. }
  39034. }
  39035. var engine = scene.getEngine();
  39036. // Lights
  39037. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39038. // Textures
  39039. if (defines._areTexturesDirty) {
  39040. defines._needUVs = false;
  39041. defines.MAINUV1 = false;
  39042. defines.MAINUV2 = false;
  39043. if (scene.texturesEnabled) {
  39044. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39045. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39046. return false;
  39047. }
  39048. else {
  39049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39050. }
  39051. }
  39052. else {
  39053. defines.DIFFUSE = false;
  39054. }
  39055. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39056. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39057. return false;
  39058. }
  39059. else {
  39060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39061. }
  39062. }
  39063. else {
  39064. defines.AMBIENT = false;
  39065. }
  39066. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39067. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39068. return false;
  39069. }
  39070. else {
  39071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39072. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39073. }
  39074. }
  39075. else {
  39076. defines.OPACITY = false;
  39077. }
  39078. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39079. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39080. return false;
  39081. }
  39082. else {
  39083. defines._needNormals = true;
  39084. defines.REFLECTION = true;
  39085. defines.ROUGHNESS = (this._roughness > 0);
  39086. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39087. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39088. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39089. switch (this._reflectionTexture.coordinatesMode) {
  39090. case BABYLON.Texture.CUBIC_MODE:
  39091. case BABYLON.Texture.INVCUBIC_MODE:
  39092. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39093. break;
  39094. case BABYLON.Texture.EXPLICIT_MODE:
  39095. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39096. break;
  39097. case BABYLON.Texture.PLANAR_MODE:
  39098. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39099. break;
  39100. case BABYLON.Texture.PROJECTION_MODE:
  39101. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39102. break;
  39103. case BABYLON.Texture.SKYBOX_MODE:
  39104. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39105. break;
  39106. case BABYLON.Texture.SPHERICAL_MODE:
  39107. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39108. break;
  39109. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39110. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39111. break;
  39112. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39113. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39114. break;
  39115. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39116. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39117. break;
  39118. }
  39119. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39120. }
  39121. }
  39122. else {
  39123. defines.REFLECTION = false;
  39124. }
  39125. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39126. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39127. return false;
  39128. }
  39129. else {
  39130. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39131. }
  39132. }
  39133. else {
  39134. defines.EMISSIVE = false;
  39135. }
  39136. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39137. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39138. return false;
  39139. }
  39140. else {
  39141. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39142. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39143. }
  39144. }
  39145. else {
  39146. defines.LIGHTMAP = false;
  39147. }
  39148. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39149. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39150. return false;
  39151. }
  39152. else {
  39153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39154. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39155. }
  39156. }
  39157. else {
  39158. defines.SPECULAR = false;
  39159. }
  39160. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39161. // Bump texure can not be not blocking.
  39162. if (!this._bumpTexture.isReady()) {
  39163. return false;
  39164. }
  39165. else {
  39166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39167. defines.PARALLAX = this._useParallax;
  39168. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39169. }
  39170. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39171. }
  39172. else {
  39173. defines.BUMP = false;
  39174. }
  39175. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39176. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39177. return false;
  39178. }
  39179. else {
  39180. defines._needUVs = true;
  39181. defines.REFRACTION = true;
  39182. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39183. }
  39184. }
  39185. else {
  39186. defines.REFRACTION = false;
  39187. }
  39188. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39189. }
  39190. else {
  39191. defines.DIFFUSE = false;
  39192. defines.AMBIENT = false;
  39193. defines.OPACITY = false;
  39194. defines.REFLECTION = false;
  39195. defines.EMISSIVE = false;
  39196. defines.LIGHTMAP = false;
  39197. defines.BUMP = false;
  39198. defines.REFRACTION = false;
  39199. }
  39200. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39201. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39202. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39203. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39204. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39205. }
  39206. if (defines._areImageProcessingDirty) {
  39207. if (!this._imageProcessingConfiguration.isReady()) {
  39208. return false;
  39209. }
  39210. this._imageProcessingConfiguration.prepareDefines(defines);
  39211. }
  39212. if (defines._areFresnelDirty) {
  39213. if (StandardMaterial.FresnelEnabled) {
  39214. // Fresnel
  39215. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39216. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39217. this._reflectionFresnelParameters) {
  39218. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39219. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39220. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39221. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39222. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39223. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39224. defines._needNormals = true;
  39225. defines.FRESNEL = true;
  39226. }
  39227. }
  39228. else {
  39229. defines.FRESNEL = false;
  39230. }
  39231. }
  39232. // Misc.
  39233. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39234. // Attribs
  39235. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39236. // Values that need to be evaluated on every frame
  39237. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39238. // Get correct effect
  39239. if (defines.isDirty) {
  39240. defines.markAsProcessed();
  39241. scene.resetCachedMaterial();
  39242. // Fallbacks
  39243. var fallbacks = new BABYLON.EffectFallbacks();
  39244. if (defines.REFLECTION) {
  39245. fallbacks.addFallback(0, "REFLECTION");
  39246. }
  39247. if (defines.SPECULAR) {
  39248. fallbacks.addFallback(0, "SPECULAR");
  39249. }
  39250. if (defines.BUMP) {
  39251. fallbacks.addFallback(0, "BUMP");
  39252. }
  39253. if (defines.PARALLAX) {
  39254. fallbacks.addFallback(1, "PARALLAX");
  39255. }
  39256. if (defines.PARALLAXOCCLUSION) {
  39257. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39258. }
  39259. if (defines.SPECULAROVERALPHA) {
  39260. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39261. }
  39262. if (defines.FOG) {
  39263. fallbacks.addFallback(1, "FOG");
  39264. }
  39265. if (defines.POINTSIZE) {
  39266. fallbacks.addFallback(0, "POINTSIZE");
  39267. }
  39268. if (defines.LOGARITHMICDEPTH) {
  39269. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39270. }
  39271. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39272. if (defines.SPECULARTERM) {
  39273. fallbacks.addFallback(0, "SPECULARTERM");
  39274. }
  39275. if (defines.DIFFUSEFRESNEL) {
  39276. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39277. }
  39278. if (defines.OPACITYFRESNEL) {
  39279. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39280. }
  39281. if (defines.REFLECTIONFRESNEL) {
  39282. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39283. }
  39284. if (defines.EMISSIVEFRESNEL) {
  39285. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39286. }
  39287. if (defines.FRESNEL) {
  39288. fallbacks.addFallback(4, "FRESNEL");
  39289. }
  39290. //Attributes
  39291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39292. if (defines.NORMAL) {
  39293. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39294. }
  39295. if (defines.UV1) {
  39296. attribs.push(BABYLON.VertexBuffer.UVKind);
  39297. }
  39298. if (defines.UV2) {
  39299. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39300. }
  39301. if (defines.VERTEXCOLOR) {
  39302. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39303. }
  39304. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39305. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39306. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39307. var shaderName = "default";
  39308. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39309. "vFogInfos", "vFogColor", "pointSize",
  39310. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39311. "mBones",
  39312. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39313. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39314. "vReflectionPosition", "vReflectionSize",
  39315. "logarithmicDepthConstant", "vTangentSpaceParams"
  39316. ];
  39317. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39318. var uniformBuffers = ["Material", "Scene"];
  39319. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39320. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39321. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39322. uniformsNames: uniforms,
  39323. uniformBuffersNames: uniformBuffers,
  39324. samplers: samplers,
  39325. defines: defines,
  39326. maxSimultaneousLights: this._maxSimultaneousLights
  39327. });
  39328. if (this.customShaderNameResolve) {
  39329. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39330. }
  39331. var join = defines.toString();
  39332. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39333. attributes: attribs,
  39334. uniformsNames: uniforms,
  39335. uniformBuffersNames: uniformBuffers,
  39336. samplers: samplers,
  39337. defines: join,
  39338. fallbacks: fallbacks,
  39339. onCompiled: this.onCompiled,
  39340. onError: this.onError,
  39341. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39342. }, engine), defines);
  39343. this.buildUniformLayout();
  39344. }
  39345. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39346. return false;
  39347. }
  39348. defines._renderId = scene.getRenderId();
  39349. this._wasPreviouslyReady = true;
  39350. return true;
  39351. };
  39352. StandardMaterial.prototype.buildUniformLayout = function () {
  39353. // Order is important !
  39354. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39355. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39356. this._uniformBuffer.addUniform("opacityParts", 4);
  39357. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39358. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39359. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39360. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39361. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39362. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39363. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39364. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39365. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39366. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39367. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39368. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39369. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39370. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39371. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39372. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39373. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39374. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39375. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39376. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39377. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39378. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39379. this._uniformBuffer.addUniform("specularMatrix", 16);
  39380. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39381. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39382. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39383. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39384. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39385. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39386. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39387. this._uniformBuffer.addUniform("pointSize", 1);
  39388. this._uniformBuffer.create();
  39389. };
  39390. StandardMaterial.prototype.unbind = function () {
  39391. if (this._activeEffect) {
  39392. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39393. this._activeEffect.setTexture("reflection2DSampler", null);
  39394. }
  39395. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39396. this._activeEffect.setTexture("refraction2DSampler", null);
  39397. }
  39398. }
  39399. _super.prototype.unbind.call(this);
  39400. };
  39401. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39402. var scene = this.getScene();
  39403. var defines = subMesh._materialDefines;
  39404. if (!defines) {
  39405. return;
  39406. }
  39407. var effect = subMesh.effect;
  39408. if (!effect) {
  39409. return;
  39410. }
  39411. this._activeEffect = effect;
  39412. // Matrices
  39413. this.bindOnlyWorldMatrix(world);
  39414. // Normal Matrix
  39415. if (defines.OBJECTSPACE_NORMALMAP) {
  39416. world.toNormalMatrix(this._normalMatrix);
  39417. this.bindOnlyNormalMatrix(this._normalMatrix);
  39418. }
  39419. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39420. // Bones
  39421. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39422. if (mustRebind) {
  39423. this._uniformBuffer.bindToEffect(effect, "Material");
  39424. this.bindViewProjection(effect);
  39425. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39426. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39427. // Fresnel
  39428. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39429. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39430. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39431. }
  39432. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39433. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39434. }
  39435. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39436. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39437. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39438. }
  39439. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39440. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39441. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39442. }
  39443. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39444. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39445. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39446. }
  39447. }
  39448. // Textures
  39449. if (scene.texturesEnabled) {
  39450. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39451. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39452. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39453. }
  39454. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39455. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39456. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39457. }
  39458. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39459. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39460. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39461. }
  39462. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39463. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39464. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39465. if (this._reflectionTexture.boundingBoxSize) {
  39466. var cubeTexture = this._reflectionTexture;
  39467. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39468. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39469. }
  39470. }
  39471. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39472. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39473. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39474. }
  39475. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39476. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39477. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39478. }
  39479. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39480. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39481. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39482. }
  39483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39484. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39485. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39486. if (scene._mirroredCameraPosition) {
  39487. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39488. }
  39489. else {
  39490. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39491. }
  39492. }
  39493. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39494. var depth = 1.0;
  39495. if (!this._refractionTexture.isCube) {
  39496. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39497. if (this._refractionTexture.depth) {
  39498. depth = this._refractionTexture.depth;
  39499. }
  39500. }
  39501. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39502. }
  39503. }
  39504. // Point size
  39505. if (this.pointsCloud) {
  39506. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39507. }
  39508. if (defines.SPECULARTERM) {
  39509. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39510. }
  39511. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39512. // Diffuse
  39513. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39514. }
  39515. // Textures
  39516. if (scene.texturesEnabled) {
  39517. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39518. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39519. }
  39520. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39521. effect.setTexture("ambientSampler", this._ambientTexture);
  39522. }
  39523. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39524. effect.setTexture("opacitySampler", this._opacityTexture);
  39525. }
  39526. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39527. if (this._reflectionTexture.isCube) {
  39528. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39529. }
  39530. else {
  39531. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39532. }
  39533. }
  39534. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39535. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39536. }
  39537. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39538. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39539. }
  39540. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39541. effect.setTexture("specularSampler", this._specularTexture);
  39542. }
  39543. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39544. effect.setTexture("bumpSampler", this._bumpTexture);
  39545. }
  39546. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39547. var depth = 1.0;
  39548. if (this._refractionTexture.isCube) {
  39549. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39550. }
  39551. else {
  39552. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39553. }
  39554. }
  39555. }
  39556. // Clip plane
  39557. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39558. // Colors
  39559. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39560. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39561. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39562. }
  39563. if (mustRebind || !this.isFrozen) {
  39564. // Lights
  39565. if (scene.lightsEnabled && !this._disableLighting) {
  39566. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39567. }
  39568. // View
  39569. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39570. this.bindView(effect);
  39571. }
  39572. // Fog
  39573. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39574. // Morph targets
  39575. if (defines.NUM_MORPH_INFLUENCERS) {
  39576. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39577. }
  39578. // Log. depth
  39579. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39580. // image processing
  39581. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39582. this._imageProcessingConfiguration.bind(this._activeEffect);
  39583. }
  39584. }
  39585. this._uniformBuffer.update();
  39586. this._afterBind(mesh, this._activeEffect);
  39587. };
  39588. StandardMaterial.prototype.getAnimatables = function () {
  39589. var results = [];
  39590. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39591. results.push(this._diffuseTexture);
  39592. }
  39593. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39594. results.push(this._ambientTexture);
  39595. }
  39596. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39597. results.push(this._opacityTexture);
  39598. }
  39599. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39600. results.push(this._reflectionTexture);
  39601. }
  39602. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39603. results.push(this._emissiveTexture);
  39604. }
  39605. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39606. results.push(this._specularTexture);
  39607. }
  39608. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39609. results.push(this._bumpTexture);
  39610. }
  39611. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39612. results.push(this._lightmapTexture);
  39613. }
  39614. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39615. results.push(this._refractionTexture);
  39616. }
  39617. return results;
  39618. };
  39619. StandardMaterial.prototype.getActiveTextures = function () {
  39620. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39621. if (this._diffuseTexture) {
  39622. activeTextures.push(this._diffuseTexture);
  39623. }
  39624. if (this._ambientTexture) {
  39625. activeTextures.push(this._ambientTexture);
  39626. }
  39627. if (this._opacityTexture) {
  39628. activeTextures.push(this._opacityTexture);
  39629. }
  39630. if (this._reflectionTexture) {
  39631. activeTextures.push(this._reflectionTexture);
  39632. }
  39633. if (this._emissiveTexture) {
  39634. activeTextures.push(this._emissiveTexture);
  39635. }
  39636. if (this._specularTexture) {
  39637. activeTextures.push(this._specularTexture);
  39638. }
  39639. if (this._bumpTexture) {
  39640. activeTextures.push(this._bumpTexture);
  39641. }
  39642. if (this._lightmapTexture) {
  39643. activeTextures.push(this._lightmapTexture);
  39644. }
  39645. if (this._refractionTexture) {
  39646. activeTextures.push(this._refractionTexture);
  39647. }
  39648. return activeTextures;
  39649. };
  39650. StandardMaterial.prototype.hasTexture = function (texture) {
  39651. if (_super.prototype.hasTexture.call(this, texture)) {
  39652. return true;
  39653. }
  39654. if (this._diffuseTexture === texture) {
  39655. return true;
  39656. }
  39657. if (this._ambientTexture === texture) {
  39658. return true;
  39659. }
  39660. if (this._opacityTexture === texture) {
  39661. return true;
  39662. }
  39663. if (this._reflectionTexture === texture) {
  39664. return true;
  39665. }
  39666. if (this._emissiveTexture === texture) {
  39667. return true;
  39668. }
  39669. if (this._specularTexture === texture) {
  39670. return true;
  39671. }
  39672. if (this._bumpTexture === texture) {
  39673. return true;
  39674. }
  39675. if (this._lightmapTexture === texture) {
  39676. return true;
  39677. }
  39678. if (this._refractionTexture === texture) {
  39679. return true;
  39680. }
  39681. return false;
  39682. };
  39683. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39684. if (forceDisposeTextures) {
  39685. if (this._diffuseTexture) {
  39686. this._diffuseTexture.dispose();
  39687. }
  39688. if (this._ambientTexture) {
  39689. this._ambientTexture.dispose();
  39690. }
  39691. if (this._opacityTexture) {
  39692. this._opacityTexture.dispose();
  39693. }
  39694. if (this._reflectionTexture) {
  39695. this._reflectionTexture.dispose();
  39696. }
  39697. if (this._emissiveTexture) {
  39698. this._emissiveTexture.dispose();
  39699. }
  39700. if (this._specularTexture) {
  39701. this._specularTexture.dispose();
  39702. }
  39703. if (this._bumpTexture) {
  39704. this._bumpTexture.dispose();
  39705. }
  39706. if (this._lightmapTexture) {
  39707. this._lightmapTexture.dispose();
  39708. }
  39709. if (this._refractionTexture) {
  39710. this._refractionTexture.dispose();
  39711. }
  39712. }
  39713. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39714. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39715. }
  39716. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39717. };
  39718. StandardMaterial.prototype.clone = function (name) {
  39719. var _this = this;
  39720. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39721. result.name = name;
  39722. result.id = name;
  39723. return result;
  39724. };
  39725. StandardMaterial.prototype.serialize = function () {
  39726. return BABYLON.SerializationHelper.Serialize(this);
  39727. };
  39728. // Statics
  39729. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39730. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39731. };
  39732. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39733. get: function () {
  39734. return StandardMaterial._DiffuseTextureEnabled;
  39735. },
  39736. set: function (value) {
  39737. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39738. return;
  39739. }
  39740. StandardMaterial._DiffuseTextureEnabled = value;
  39741. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39742. },
  39743. enumerable: true,
  39744. configurable: true
  39745. });
  39746. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39747. get: function () {
  39748. return StandardMaterial._AmbientTextureEnabled;
  39749. },
  39750. set: function (value) {
  39751. if (StandardMaterial._AmbientTextureEnabled === value) {
  39752. return;
  39753. }
  39754. StandardMaterial._AmbientTextureEnabled = value;
  39755. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39756. },
  39757. enumerable: true,
  39758. configurable: true
  39759. });
  39760. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39761. get: function () {
  39762. return StandardMaterial._OpacityTextureEnabled;
  39763. },
  39764. set: function (value) {
  39765. if (StandardMaterial._OpacityTextureEnabled === value) {
  39766. return;
  39767. }
  39768. StandardMaterial._OpacityTextureEnabled = value;
  39769. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39770. },
  39771. enumerable: true,
  39772. configurable: true
  39773. });
  39774. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39775. get: function () {
  39776. return StandardMaterial._ReflectionTextureEnabled;
  39777. },
  39778. set: function (value) {
  39779. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39780. return;
  39781. }
  39782. StandardMaterial._ReflectionTextureEnabled = value;
  39783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39784. },
  39785. enumerable: true,
  39786. configurable: true
  39787. });
  39788. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39789. get: function () {
  39790. return StandardMaterial._EmissiveTextureEnabled;
  39791. },
  39792. set: function (value) {
  39793. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39794. return;
  39795. }
  39796. StandardMaterial._EmissiveTextureEnabled = value;
  39797. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39798. },
  39799. enumerable: true,
  39800. configurable: true
  39801. });
  39802. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39803. get: function () {
  39804. return StandardMaterial._SpecularTextureEnabled;
  39805. },
  39806. set: function (value) {
  39807. if (StandardMaterial._SpecularTextureEnabled === value) {
  39808. return;
  39809. }
  39810. StandardMaterial._SpecularTextureEnabled = value;
  39811. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39812. },
  39813. enumerable: true,
  39814. configurable: true
  39815. });
  39816. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39817. get: function () {
  39818. return StandardMaterial._BumpTextureEnabled;
  39819. },
  39820. set: function (value) {
  39821. if (StandardMaterial._BumpTextureEnabled === value) {
  39822. return;
  39823. }
  39824. StandardMaterial._BumpTextureEnabled = value;
  39825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39831. get: function () {
  39832. return StandardMaterial._LightmapTextureEnabled;
  39833. },
  39834. set: function (value) {
  39835. if (StandardMaterial._LightmapTextureEnabled === value) {
  39836. return;
  39837. }
  39838. StandardMaterial._LightmapTextureEnabled = value;
  39839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39840. },
  39841. enumerable: true,
  39842. configurable: true
  39843. });
  39844. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39845. get: function () {
  39846. return StandardMaterial._RefractionTextureEnabled;
  39847. },
  39848. set: function (value) {
  39849. if (StandardMaterial._RefractionTextureEnabled === value) {
  39850. return;
  39851. }
  39852. StandardMaterial._RefractionTextureEnabled = value;
  39853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39854. },
  39855. enumerable: true,
  39856. configurable: true
  39857. });
  39858. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39859. get: function () {
  39860. return StandardMaterial._ColorGradingTextureEnabled;
  39861. },
  39862. set: function (value) {
  39863. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39864. return;
  39865. }
  39866. StandardMaterial._ColorGradingTextureEnabled = value;
  39867. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39873. get: function () {
  39874. return StandardMaterial._FresnelEnabled;
  39875. },
  39876. set: function (value) {
  39877. if (StandardMaterial._FresnelEnabled === value) {
  39878. return;
  39879. }
  39880. StandardMaterial._FresnelEnabled = value;
  39881. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39882. },
  39883. enumerable: true,
  39884. configurable: true
  39885. });
  39886. // Flags used to enable or disable a type of texture for all Standard Materials
  39887. StandardMaterial._DiffuseTextureEnabled = true;
  39888. StandardMaterial._AmbientTextureEnabled = true;
  39889. StandardMaterial._OpacityTextureEnabled = true;
  39890. StandardMaterial._ReflectionTextureEnabled = true;
  39891. StandardMaterial._EmissiveTextureEnabled = true;
  39892. StandardMaterial._SpecularTextureEnabled = true;
  39893. StandardMaterial._BumpTextureEnabled = true;
  39894. StandardMaterial._LightmapTextureEnabled = true;
  39895. StandardMaterial._RefractionTextureEnabled = true;
  39896. StandardMaterial._ColorGradingTextureEnabled = true;
  39897. StandardMaterial._FresnelEnabled = true;
  39898. __decorate([
  39899. BABYLON.serializeAsTexture("diffuseTexture")
  39900. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39901. __decorate([
  39902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39903. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39904. __decorate([
  39905. BABYLON.serializeAsTexture("ambientTexture")
  39906. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39907. __decorate([
  39908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39909. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39910. __decorate([
  39911. BABYLON.serializeAsTexture("opacityTexture")
  39912. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39913. __decorate([
  39914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39915. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39916. __decorate([
  39917. BABYLON.serializeAsTexture("reflectionTexture")
  39918. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39919. __decorate([
  39920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39921. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39922. __decorate([
  39923. BABYLON.serializeAsTexture("emissiveTexture")
  39924. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39925. __decorate([
  39926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39927. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39928. __decorate([
  39929. BABYLON.serializeAsTexture("specularTexture")
  39930. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39931. __decorate([
  39932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39933. ], StandardMaterial.prototype, "specularTexture", void 0);
  39934. __decorate([
  39935. BABYLON.serializeAsTexture("bumpTexture")
  39936. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39937. __decorate([
  39938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39939. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39940. __decorate([
  39941. BABYLON.serializeAsTexture("lightmapTexture")
  39942. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39943. __decorate([
  39944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39945. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39946. __decorate([
  39947. BABYLON.serializeAsTexture("refractionTexture")
  39948. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39949. __decorate([
  39950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39951. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39952. __decorate([
  39953. BABYLON.serializeAsColor3("ambient")
  39954. ], StandardMaterial.prototype, "ambientColor", void 0);
  39955. __decorate([
  39956. BABYLON.serializeAsColor3("diffuse")
  39957. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39958. __decorate([
  39959. BABYLON.serializeAsColor3("specular")
  39960. ], StandardMaterial.prototype, "specularColor", void 0);
  39961. __decorate([
  39962. BABYLON.serializeAsColor3("emissive")
  39963. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39964. __decorate([
  39965. BABYLON.serialize()
  39966. ], StandardMaterial.prototype, "specularPower", void 0);
  39967. __decorate([
  39968. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39969. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39970. __decorate([
  39971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39972. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39973. __decorate([
  39974. BABYLON.serialize("useEmissiveAsIllumination")
  39975. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39976. __decorate([
  39977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39978. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39979. __decorate([
  39980. BABYLON.serialize("linkEmissiveWithDiffuse")
  39981. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39982. __decorate([
  39983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39984. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39985. __decorate([
  39986. BABYLON.serialize("useSpecularOverAlpha")
  39987. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39988. __decorate([
  39989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39990. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39991. __decorate([
  39992. BABYLON.serialize("useReflectionOverAlpha")
  39993. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39994. __decorate([
  39995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39996. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39997. __decorate([
  39998. BABYLON.serialize("disableLighting")
  39999. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40000. __decorate([
  40001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40002. ], StandardMaterial.prototype, "disableLighting", void 0);
  40003. __decorate([
  40004. BABYLON.serialize("useObjectSpaceNormalMap")
  40005. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40006. __decorate([
  40007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40008. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40009. __decorate([
  40010. BABYLON.serialize("useParallax")
  40011. ], StandardMaterial.prototype, "_useParallax", void 0);
  40012. __decorate([
  40013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40014. ], StandardMaterial.prototype, "useParallax", void 0);
  40015. __decorate([
  40016. BABYLON.serialize("useParallaxOcclusion")
  40017. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40018. __decorate([
  40019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40020. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40021. __decorate([
  40022. BABYLON.serialize()
  40023. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40024. __decorate([
  40025. BABYLON.serialize("roughness")
  40026. ], StandardMaterial.prototype, "_roughness", void 0);
  40027. __decorate([
  40028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40029. ], StandardMaterial.prototype, "roughness", void 0);
  40030. __decorate([
  40031. BABYLON.serialize()
  40032. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40033. __decorate([
  40034. BABYLON.serialize()
  40035. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40036. __decorate([
  40037. BABYLON.serialize("useLightmapAsShadowmap")
  40038. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40039. __decorate([
  40040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40041. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40042. __decorate([
  40043. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40044. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40045. __decorate([
  40046. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40047. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40048. __decorate([
  40049. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40050. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40051. __decorate([
  40052. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40053. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40054. __decorate([
  40055. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40056. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40057. __decorate([
  40058. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40059. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40060. __decorate([
  40061. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40062. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40063. __decorate([
  40064. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40065. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40066. __decorate([
  40067. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40068. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40069. __decorate([
  40070. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40071. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40072. __decorate([
  40073. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40074. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40075. __decorate([
  40076. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40077. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40078. __decorate([
  40079. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40080. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40081. __decorate([
  40082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40083. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40084. __decorate([
  40085. BABYLON.serialize("maxSimultaneousLights")
  40086. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40087. __decorate([
  40088. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40089. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40090. __decorate([
  40091. BABYLON.serialize("invertNormalMapX")
  40092. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40093. __decorate([
  40094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40095. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40096. __decorate([
  40097. BABYLON.serialize("invertNormalMapY")
  40098. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40099. __decorate([
  40100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40101. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40102. __decorate([
  40103. BABYLON.serialize("twoSidedLighting")
  40104. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40105. __decorate([
  40106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40107. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40108. __decorate([
  40109. BABYLON.serialize()
  40110. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40111. return StandardMaterial;
  40112. }(BABYLON.PushMaterial));
  40113. BABYLON.StandardMaterial = StandardMaterial;
  40114. })(BABYLON || (BABYLON = {}));
  40115. //# sourceMappingURL=babylon.standardMaterial.js.map
  40116. var BABYLON;
  40117. (function (BABYLON) {
  40118. /**
  40119. * Manages the defines for the PBR Material.
  40120. */
  40121. var PBRMaterialDefines = /** @class */ (function (_super) {
  40122. __extends(PBRMaterialDefines, _super);
  40123. /**
  40124. * Initializes the PBR Material defines.
  40125. */
  40126. function PBRMaterialDefines() {
  40127. var _this = _super.call(this) || this;
  40128. _this.PBR = true;
  40129. _this.MAINUV1 = false;
  40130. _this.MAINUV2 = false;
  40131. _this.UV1 = false;
  40132. _this.UV2 = false;
  40133. _this.ALBEDO = false;
  40134. _this.ALBEDODIRECTUV = 0;
  40135. _this.VERTEXCOLOR = false;
  40136. _this.AMBIENT = false;
  40137. _this.AMBIENTDIRECTUV = 0;
  40138. _this.AMBIENTINGRAYSCALE = false;
  40139. _this.OPACITY = false;
  40140. _this.VERTEXALPHA = false;
  40141. _this.OPACITYDIRECTUV = 0;
  40142. _this.OPACITYRGB = false;
  40143. _this.ALPHATEST = false;
  40144. _this.DEPTHPREPASS = false;
  40145. _this.ALPHABLEND = false;
  40146. _this.ALPHAFROMALBEDO = false;
  40147. _this.ALPHATESTVALUE = 0.5;
  40148. _this.SPECULAROVERALPHA = false;
  40149. _this.RADIANCEOVERALPHA = false;
  40150. _this.ALPHAFRESNEL = false;
  40151. _this.LINEARALPHAFRESNEL = false;
  40152. _this.PREMULTIPLYALPHA = false;
  40153. _this.EMISSIVE = false;
  40154. _this.EMISSIVEDIRECTUV = 0;
  40155. _this.REFLECTIVITY = false;
  40156. _this.REFLECTIVITYDIRECTUV = 0;
  40157. _this.SPECULARTERM = false;
  40158. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40159. _this.MICROSURFACEAUTOMATIC = false;
  40160. _this.LODBASEDMICROSFURACE = false;
  40161. _this.MICROSURFACEMAP = false;
  40162. _this.MICROSURFACEMAPDIRECTUV = 0;
  40163. _this.METALLICWORKFLOW = false;
  40164. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40165. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40166. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40167. _this.AOSTOREINMETALMAPRED = false;
  40168. _this.ENVIRONMENTBRDF = false;
  40169. _this.NORMAL = false;
  40170. _this.TANGENT = false;
  40171. _this.BUMP = false;
  40172. _this.BUMPDIRECTUV = 0;
  40173. _this.OBJECTSPACE_NORMALMAP = false;
  40174. _this.PARALLAX = false;
  40175. _this.PARALLAXOCCLUSION = false;
  40176. _this.NORMALXYSCALE = true;
  40177. _this.LIGHTMAP = false;
  40178. _this.LIGHTMAPDIRECTUV = 0;
  40179. _this.USELIGHTMAPASSHADOWMAP = false;
  40180. _this.REFLECTION = false;
  40181. _this.REFLECTIONMAP_3D = false;
  40182. _this.REFLECTIONMAP_SPHERICAL = false;
  40183. _this.REFLECTIONMAP_PLANAR = false;
  40184. _this.REFLECTIONMAP_CUBIC = false;
  40185. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40186. _this.REFLECTIONMAP_PROJECTION = false;
  40187. _this.REFLECTIONMAP_SKYBOX = false;
  40188. _this.REFLECTIONMAP_EXPLICIT = false;
  40189. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40190. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40191. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40192. _this.INVERTCUBICMAP = false;
  40193. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40194. _this.USESPHERICALINVERTEX = false;
  40195. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40196. _this.LODINREFLECTIONALPHA = false;
  40197. _this.GAMMAREFLECTION = false;
  40198. _this.RADIANCEOCCLUSION = false;
  40199. _this.HORIZONOCCLUSION = false;
  40200. _this.REFRACTION = false;
  40201. _this.REFRACTIONMAP_3D = false;
  40202. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40203. _this.LODINREFRACTIONALPHA = false;
  40204. _this.GAMMAREFRACTION = false;
  40205. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40206. _this.INSTANCES = false;
  40207. _this.NUM_BONE_INFLUENCERS = 0;
  40208. _this.BonesPerMesh = 0;
  40209. _this.NONUNIFORMSCALING = false;
  40210. _this.MORPHTARGETS = false;
  40211. _this.MORPHTARGETS_NORMAL = false;
  40212. _this.MORPHTARGETS_TANGENT = false;
  40213. _this.NUM_MORPH_INFLUENCERS = 0;
  40214. _this.IMAGEPROCESSING = false;
  40215. _this.VIGNETTE = false;
  40216. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40217. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40218. _this.TONEMAPPING = false;
  40219. _this.CONTRAST = false;
  40220. _this.COLORCURVES = false;
  40221. _this.COLORGRADING = false;
  40222. _this.COLORGRADING3D = false;
  40223. _this.SAMPLER3DGREENDEPTH = false;
  40224. _this.SAMPLER3DBGRMAP = false;
  40225. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40226. _this.EXPOSURE = false;
  40227. _this.USEPHYSICALLIGHTFALLOFF = false;
  40228. _this.TWOSIDEDLIGHTING = false;
  40229. _this.SHADOWFLOAT = false;
  40230. _this.CLIPPLANE = false;
  40231. _this.POINTSIZE = false;
  40232. _this.FOG = false;
  40233. _this.LOGARITHMICDEPTH = false;
  40234. _this.FORCENORMALFORWARD = false;
  40235. _this.rebuild();
  40236. return _this;
  40237. }
  40238. /**
  40239. * Resets the PBR Material defines.
  40240. */
  40241. PBRMaterialDefines.prototype.reset = function () {
  40242. _super.prototype.reset.call(this);
  40243. this.ALPHATESTVALUE = 0.5;
  40244. this.PBR = true;
  40245. };
  40246. return PBRMaterialDefines;
  40247. }(BABYLON.MaterialDefines));
  40248. /**
  40249. * The Physically based material base class of BJS.
  40250. *
  40251. * This offers the main features of a standard PBR material.
  40252. * For more information, please refer to the documentation :
  40253. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40254. */
  40255. var PBRBaseMaterial = /** @class */ (function (_super) {
  40256. __extends(PBRBaseMaterial, _super);
  40257. /**
  40258. * Instantiates a new PBRMaterial instance.
  40259. *
  40260. * @param name The material name
  40261. * @param scene The scene the material will be use in.
  40262. */
  40263. function PBRBaseMaterial(name, scene) {
  40264. var _this = _super.call(this, name, scene) || this;
  40265. /**
  40266. * Intensity of the direct lights e.g. the four lights available in your scene.
  40267. * This impacts both the direct diffuse and specular highlights.
  40268. */
  40269. _this._directIntensity = 1.0;
  40270. /**
  40271. * Intensity of the emissive part of the material.
  40272. * This helps controlling the emissive effect without modifying the emissive color.
  40273. */
  40274. _this._emissiveIntensity = 1.0;
  40275. /**
  40276. * Intensity of the environment e.g. how much the environment will light the object
  40277. * either through harmonics for rough material or through the refelction for shiny ones.
  40278. */
  40279. _this._environmentIntensity = 1.0;
  40280. /**
  40281. * This is a special control allowing the reduction of the specular highlights coming from the
  40282. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40283. */
  40284. _this._specularIntensity = 1.0;
  40285. /**
  40286. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40287. */
  40288. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40289. /**
  40290. * Debug Control allowing disabling the bump map on this material.
  40291. */
  40292. _this._disableBumpMap = false;
  40293. /**
  40294. * AKA Occlusion Texture Intensity in other nomenclature.
  40295. */
  40296. _this._ambientTextureStrength = 1.0;
  40297. /**
  40298. * The color of a material in ambient lighting.
  40299. */
  40300. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40301. /**
  40302. * AKA Diffuse Color in other nomenclature.
  40303. */
  40304. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40305. /**
  40306. * AKA Specular Color in other nomenclature.
  40307. */
  40308. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40309. /**
  40310. * The color applied when light is reflected from a material.
  40311. */
  40312. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40313. /**
  40314. * The color applied when light is emitted from a material.
  40315. */
  40316. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40317. /**
  40318. * AKA Glossiness in other nomenclature.
  40319. */
  40320. _this._microSurface = 0.9;
  40321. /**
  40322. * source material index of refraction (IOR)' / 'destination material IOR.
  40323. */
  40324. _this._indexOfRefraction = 0.66;
  40325. /**
  40326. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40327. */
  40328. _this._invertRefractionY = false;
  40329. /**
  40330. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40331. * Materials half opaque for instance using refraction could benefit from this control.
  40332. */
  40333. _this._linkRefractionWithTransparency = false;
  40334. /**
  40335. * Specifies that the material will use the light map as a show map.
  40336. */
  40337. _this._useLightmapAsShadowmap = false;
  40338. /**
  40339. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40340. * makes the reflect vector face the model (under horizon).
  40341. */
  40342. _this._useHorizonOcclusion = true;
  40343. /**
  40344. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40345. * too much the area relying on ambient texture to define their ambient occlusion.
  40346. */
  40347. _this._useRadianceOcclusion = true;
  40348. /**
  40349. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40350. */
  40351. _this._useAlphaFromAlbedoTexture = false;
  40352. /**
  40353. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40354. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40355. */
  40356. _this._useSpecularOverAlpha = true;
  40357. /**
  40358. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40359. */
  40360. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40361. /**
  40362. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40363. */
  40364. _this._useRoughnessFromMetallicTextureAlpha = true;
  40365. /**
  40366. * Specifies if the metallic texture contains the roughness information in its green channel.
  40367. */
  40368. _this._useRoughnessFromMetallicTextureGreen = false;
  40369. /**
  40370. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40371. */
  40372. _this._useMetallnessFromMetallicTextureBlue = false;
  40373. /**
  40374. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40375. */
  40376. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40377. /**
  40378. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40379. */
  40380. _this._useAmbientInGrayScale = false;
  40381. /**
  40382. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40383. * The material will try to infer what glossiness each pixel should be.
  40384. */
  40385. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40386. /**
  40387. * BJS is using an harcoded light falloff based on a manually sets up range.
  40388. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40389. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40390. */
  40391. _this._usePhysicalLightFalloff = true;
  40392. /**
  40393. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40394. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40395. */
  40396. _this._useRadianceOverAlpha = true;
  40397. /**
  40398. * Allows using an object space normal map (instead of tangent space).
  40399. */
  40400. _this._useObjectSpaceNormalMap = false;
  40401. /**
  40402. * Allows using the bump map in parallax mode.
  40403. */
  40404. _this._useParallax = false;
  40405. /**
  40406. * Allows using the bump map in parallax occlusion mode.
  40407. */
  40408. _this._useParallaxOcclusion = false;
  40409. /**
  40410. * Controls the scale bias of the parallax mode.
  40411. */
  40412. _this._parallaxScaleBias = 0.05;
  40413. /**
  40414. * If sets to true, disables all the lights affecting the material.
  40415. */
  40416. _this._disableLighting = false;
  40417. /**
  40418. * Number of Simultaneous lights allowed on the material.
  40419. */
  40420. _this._maxSimultaneousLights = 4;
  40421. /**
  40422. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40423. */
  40424. _this._invertNormalMapX = false;
  40425. /**
  40426. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40427. */
  40428. _this._invertNormalMapY = false;
  40429. /**
  40430. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40431. */
  40432. _this._twoSidedLighting = false;
  40433. /**
  40434. * Defines the alpha limits in alpha test mode.
  40435. */
  40436. _this._alphaCutOff = 0.4;
  40437. /**
  40438. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40439. */
  40440. _this._forceAlphaTest = false;
  40441. /**
  40442. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40443. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40444. */
  40445. _this._useAlphaFresnel = false;
  40446. /**
  40447. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40448. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40449. */
  40450. _this._useLinearAlphaFresnel = false;
  40451. /**
  40452. * The transparency mode of the material.
  40453. */
  40454. _this._transparencyMode = null;
  40455. /**
  40456. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40457. * from cos thetav and roughness:
  40458. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40459. */
  40460. _this._environmentBRDFTexture = null;
  40461. /**
  40462. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40463. */
  40464. _this._forceIrradianceInFragment = false;
  40465. /**
  40466. * Force normal to face away from face.
  40467. */
  40468. _this._forceNormalForward = false;
  40469. /**
  40470. * Force metallic workflow.
  40471. */
  40472. _this._forceMetallicWorkflow = false;
  40473. /**
  40474. * Stores the available render targets.
  40475. */
  40476. _this._renderTargets = new BABYLON.SmartArray(16);
  40477. /**
  40478. * Sets the global ambient color for the material used in lighting calculations.
  40479. */
  40480. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40481. // Setup the default processing configuration to the scene.
  40482. _this._attachImageProcessingConfiguration(null);
  40483. _this.getRenderTargetTextures = function () {
  40484. _this._renderTargets.reset();
  40485. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40486. _this._renderTargets.push(_this._reflectionTexture);
  40487. }
  40488. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40489. _this._renderTargets.push(_this._refractionTexture);
  40490. }
  40491. return _this._renderTargets;
  40492. };
  40493. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40494. return _this;
  40495. }
  40496. /**
  40497. * Attaches a new image processing configuration to the PBR Material.
  40498. * @param configuration
  40499. */
  40500. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40501. var _this = this;
  40502. if (configuration === this._imageProcessingConfiguration) {
  40503. return;
  40504. }
  40505. // Detaches observer.
  40506. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40507. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40508. }
  40509. // Pick the scene configuration if needed.
  40510. if (!configuration) {
  40511. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40512. }
  40513. else {
  40514. this._imageProcessingConfiguration = configuration;
  40515. }
  40516. // Attaches observer.
  40517. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40518. _this._markAllSubMeshesAsImageProcessingDirty();
  40519. });
  40520. };
  40521. /**
  40522. * Gets the name of the material class.
  40523. */
  40524. PBRBaseMaterial.prototype.getClassName = function () {
  40525. return "PBRBaseMaterial";
  40526. };
  40527. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40528. /**
  40529. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40530. */
  40531. get: function () {
  40532. return this._useLogarithmicDepth;
  40533. },
  40534. /**
  40535. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40536. */
  40537. set: function (value) {
  40538. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40539. },
  40540. enumerable: true,
  40541. configurable: true
  40542. });
  40543. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40544. /**
  40545. * Gets the current transparency mode.
  40546. */
  40547. get: function () {
  40548. return this._transparencyMode;
  40549. },
  40550. /**
  40551. * Sets the transparency mode of the material.
  40552. */
  40553. set: function (value) {
  40554. if (this._transparencyMode === value) {
  40555. return;
  40556. }
  40557. this._transparencyMode = value;
  40558. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40559. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40565. /**
  40566. * Returns true if alpha blending should be disabled.
  40567. */
  40568. get: function () {
  40569. return (this._linkRefractionWithTransparency ||
  40570. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40571. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40572. },
  40573. enumerable: true,
  40574. configurable: true
  40575. });
  40576. /**
  40577. * Specifies whether or not this material should be rendered in alpha blend mode.
  40578. */
  40579. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40580. if (this._disableAlphaBlending) {
  40581. return false;
  40582. }
  40583. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40584. };
  40585. /**
  40586. * Specifies if the mesh will require alpha blending.
  40587. * @param mesh - BJS mesh.
  40588. */
  40589. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40590. if (this._disableAlphaBlending) {
  40591. return false;
  40592. }
  40593. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40594. };
  40595. /**
  40596. * Specifies whether or not this material should be rendered in alpha test mode.
  40597. */
  40598. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40599. if (this._forceAlphaTest) {
  40600. return true;
  40601. }
  40602. if (this._linkRefractionWithTransparency) {
  40603. return false;
  40604. }
  40605. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40606. };
  40607. /**
  40608. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40609. */
  40610. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40611. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40612. };
  40613. /**
  40614. * Gets the texture used for the alpha test.
  40615. */
  40616. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40617. return this._albedoTexture;
  40618. };
  40619. /**
  40620. * Specifies that the submesh is ready to be used.
  40621. * @param mesh - BJS mesh.
  40622. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40623. * @param useInstances - Specifies that instances should be used.
  40624. * @returns - boolean indicating that the submesh is ready or not.
  40625. */
  40626. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40627. if (subMesh.effect && this.isFrozen) {
  40628. if (this._wasPreviouslyReady) {
  40629. return true;
  40630. }
  40631. }
  40632. if (!subMesh._materialDefines) {
  40633. subMesh._materialDefines = new PBRMaterialDefines();
  40634. }
  40635. var defines = subMesh._materialDefines;
  40636. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40637. if (defines._renderId === this.getScene().getRenderId()) {
  40638. return true;
  40639. }
  40640. }
  40641. var scene = this.getScene();
  40642. var engine = scene.getEngine();
  40643. if (defines._areTexturesDirty) {
  40644. if (scene.texturesEnabled) {
  40645. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40646. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40647. return false;
  40648. }
  40649. }
  40650. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40651. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40652. return false;
  40653. }
  40654. }
  40655. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40656. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40657. return false;
  40658. }
  40659. }
  40660. var reflectionTexture = this._getReflectionTexture();
  40661. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40662. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40663. return false;
  40664. }
  40665. }
  40666. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40667. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40668. return false;
  40669. }
  40670. }
  40671. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40672. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40673. return false;
  40674. }
  40675. }
  40676. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40677. if (this._metallicTexture) {
  40678. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40679. return false;
  40680. }
  40681. }
  40682. else if (this._reflectivityTexture) {
  40683. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40684. return false;
  40685. }
  40686. }
  40687. if (this._microSurfaceTexture) {
  40688. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40689. return false;
  40690. }
  40691. }
  40692. }
  40693. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40694. // Bump texture cannot be not blocking.
  40695. if (!this._bumpTexture.isReady()) {
  40696. return false;
  40697. }
  40698. }
  40699. var refractionTexture = this._getRefractionTexture();
  40700. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40701. if (!refractionTexture.isReadyOrNotBlocking()) {
  40702. return false;
  40703. }
  40704. }
  40705. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40706. // This is blocking.
  40707. if (!this._environmentBRDFTexture.isReady()) {
  40708. return false;
  40709. }
  40710. }
  40711. }
  40712. }
  40713. if (defines._areImageProcessingDirty) {
  40714. if (!this._imageProcessingConfiguration.isReady()) {
  40715. return false;
  40716. }
  40717. }
  40718. if (!engine.getCaps().standardDerivatives) {
  40719. var bufferMesh = null;
  40720. if (mesh.getClassName() === "InstancedMesh") {
  40721. bufferMesh = mesh.sourceMesh;
  40722. }
  40723. else if (mesh.getClassName() === "Mesh") {
  40724. bufferMesh = mesh;
  40725. }
  40726. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40727. bufferMesh.createNormals(true);
  40728. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40729. }
  40730. }
  40731. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40732. if (effect) {
  40733. scene.resetCachedMaterial();
  40734. subMesh.setEffect(effect, defines);
  40735. this.buildUniformLayout();
  40736. }
  40737. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40738. return false;
  40739. }
  40740. defines._renderId = scene.getRenderId();
  40741. this._wasPreviouslyReady = true;
  40742. return true;
  40743. };
  40744. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40745. if (onCompiled === void 0) { onCompiled = null; }
  40746. if (onError === void 0) { onError = null; }
  40747. if (useInstances === void 0) { useInstances = null; }
  40748. if (useClipPlane === void 0) { useClipPlane = null; }
  40749. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40750. if (!defines.isDirty) {
  40751. return null;
  40752. }
  40753. defines.markAsProcessed();
  40754. var scene = this.getScene();
  40755. var engine = scene.getEngine();
  40756. // Fallbacks
  40757. var fallbacks = new BABYLON.EffectFallbacks();
  40758. var fallbackRank = 0;
  40759. if (defines.USESPHERICALINVERTEX) {
  40760. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40761. }
  40762. if (defines.FOG) {
  40763. fallbacks.addFallback(fallbackRank, "FOG");
  40764. }
  40765. if (defines.POINTSIZE) {
  40766. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40767. }
  40768. if (defines.LOGARITHMICDEPTH) {
  40769. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40770. }
  40771. if (defines.PARALLAX) {
  40772. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40773. }
  40774. if (defines.PARALLAXOCCLUSION) {
  40775. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40776. }
  40777. if (defines.ENVIRONMENTBRDF) {
  40778. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40779. }
  40780. if (defines.TANGENT) {
  40781. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40782. }
  40783. if (defines.BUMP) {
  40784. fallbacks.addFallback(fallbackRank++, "BUMP");
  40785. }
  40786. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40787. if (defines.SPECULARTERM) {
  40788. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40789. }
  40790. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40791. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40792. }
  40793. if (defines.LIGHTMAP) {
  40794. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40795. }
  40796. if (defines.NORMAL) {
  40797. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40798. }
  40799. if (defines.AMBIENT) {
  40800. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40801. }
  40802. if (defines.EMISSIVE) {
  40803. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40804. }
  40805. if (defines.VERTEXCOLOR) {
  40806. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40807. }
  40808. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40809. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40810. }
  40811. if (defines.MORPHTARGETS) {
  40812. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40813. }
  40814. //Attributes
  40815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40816. if (defines.NORMAL) {
  40817. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40818. }
  40819. if (defines.TANGENT) {
  40820. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40821. }
  40822. if (defines.UV1) {
  40823. attribs.push(BABYLON.VertexBuffer.UVKind);
  40824. }
  40825. if (defines.UV2) {
  40826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40827. }
  40828. if (defines.VERTEXCOLOR) {
  40829. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40830. }
  40831. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40832. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40833. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40834. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40835. "vFogInfos", "vFogColor", "pointSize",
  40836. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40837. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40838. "mBones",
  40839. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40840. "vLightingIntensity",
  40841. "logarithmicDepthConstant",
  40842. "vSphericalX", "vSphericalY", "vSphericalZ",
  40843. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40844. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40845. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40846. "vTangentSpaceParams"
  40847. ];
  40848. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40849. "bumpSampler", "lightmapSampler", "opacitySampler",
  40850. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40851. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40852. "microSurfaceSampler", "environmentBrdfSampler"];
  40853. var uniformBuffers = ["Material", "Scene"];
  40854. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40855. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40856. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40857. uniformsNames: uniforms,
  40858. uniformBuffersNames: uniformBuffers,
  40859. samplers: samplers,
  40860. defines: defines,
  40861. maxSimultaneousLights: this._maxSimultaneousLights
  40862. });
  40863. var join = defines.toString();
  40864. return engine.createEffect("pbr", {
  40865. attributes: attribs,
  40866. uniformsNames: uniforms,
  40867. uniformBuffersNames: uniformBuffers,
  40868. samplers: samplers,
  40869. defines: join,
  40870. fallbacks: fallbacks,
  40871. onCompiled: onCompiled,
  40872. onError: onError,
  40873. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40874. }, engine);
  40875. };
  40876. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40877. if (useInstances === void 0) { useInstances = null; }
  40878. if (useClipPlane === void 0) { useClipPlane = null; }
  40879. var scene = this.getScene();
  40880. var engine = scene.getEngine();
  40881. // Lights
  40882. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40883. defines._needNormals = true;
  40884. // Textures
  40885. if (defines._areTexturesDirty) {
  40886. defines._needUVs = false;
  40887. if (scene.texturesEnabled) {
  40888. if (scene.getEngine().getCaps().textureLOD) {
  40889. defines.LODBASEDMICROSFURACE = true;
  40890. }
  40891. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40892. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40893. }
  40894. else {
  40895. defines.ALBEDO = false;
  40896. }
  40897. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40898. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40899. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40900. }
  40901. else {
  40902. defines.AMBIENT = false;
  40903. }
  40904. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40905. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40906. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40907. }
  40908. else {
  40909. defines.OPACITY = false;
  40910. }
  40911. var reflectionTexture = this._getReflectionTexture();
  40912. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40913. defines.REFLECTION = true;
  40914. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40915. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40916. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40917. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40918. defines.INVERTCUBICMAP = true;
  40919. }
  40920. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40921. switch (reflectionTexture.coordinatesMode) {
  40922. case BABYLON.Texture.CUBIC_MODE:
  40923. case BABYLON.Texture.INVCUBIC_MODE:
  40924. defines.REFLECTIONMAP_CUBIC = true;
  40925. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40926. break;
  40927. case BABYLON.Texture.EXPLICIT_MODE:
  40928. defines.REFLECTIONMAP_EXPLICIT = true;
  40929. break;
  40930. case BABYLON.Texture.PLANAR_MODE:
  40931. defines.REFLECTIONMAP_PLANAR = true;
  40932. break;
  40933. case BABYLON.Texture.PROJECTION_MODE:
  40934. defines.REFLECTIONMAP_PROJECTION = true;
  40935. break;
  40936. case BABYLON.Texture.SKYBOX_MODE:
  40937. defines.REFLECTIONMAP_SKYBOX = true;
  40938. break;
  40939. case BABYLON.Texture.SPHERICAL_MODE:
  40940. defines.REFLECTIONMAP_SPHERICAL = true;
  40941. break;
  40942. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40943. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40944. break;
  40945. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40946. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40947. break;
  40948. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40949. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40950. break;
  40951. }
  40952. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40953. if (reflectionTexture.sphericalPolynomial) {
  40954. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40955. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40956. defines.USESPHERICALINVERTEX = false;
  40957. }
  40958. else {
  40959. defines.USESPHERICALINVERTEX = true;
  40960. }
  40961. }
  40962. }
  40963. }
  40964. else {
  40965. defines.REFLECTION = false;
  40966. defines.REFLECTIONMAP_3D = false;
  40967. defines.REFLECTIONMAP_SPHERICAL = false;
  40968. defines.REFLECTIONMAP_PLANAR = false;
  40969. defines.REFLECTIONMAP_CUBIC = false;
  40970. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40971. defines.REFLECTIONMAP_PROJECTION = false;
  40972. defines.REFLECTIONMAP_SKYBOX = false;
  40973. defines.REFLECTIONMAP_EXPLICIT = false;
  40974. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40975. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40976. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40977. defines.INVERTCUBICMAP = false;
  40978. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40979. defines.USESPHERICALINVERTEX = false;
  40980. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40981. defines.LODINREFLECTIONALPHA = false;
  40982. defines.GAMMAREFLECTION = false;
  40983. }
  40984. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40985. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40986. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40987. }
  40988. else {
  40989. defines.LIGHTMAP = false;
  40990. }
  40991. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40992. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40993. }
  40994. else {
  40995. defines.EMISSIVE = false;
  40996. }
  40997. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40998. if (this._metallicTexture) {
  40999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41000. defines.METALLICWORKFLOW = true;
  41001. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41002. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41003. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41004. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41005. }
  41006. else if (this._reflectivityTexture) {
  41007. defines.METALLICWORKFLOW = false;
  41008. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41009. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41010. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41011. }
  41012. else {
  41013. defines.METALLICWORKFLOW = false;
  41014. defines.REFLECTIVITY = false;
  41015. }
  41016. if (this._microSurfaceTexture) {
  41017. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41018. }
  41019. else {
  41020. defines.MICROSURFACEMAP = false;
  41021. }
  41022. }
  41023. else {
  41024. defines.REFLECTIVITY = false;
  41025. defines.MICROSURFACEMAP = false;
  41026. }
  41027. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41028. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41029. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41030. defines.PARALLAX = true;
  41031. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41032. }
  41033. else {
  41034. defines.PARALLAX = false;
  41035. }
  41036. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41037. }
  41038. else {
  41039. defines.BUMP = false;
  41040. }
  41041. var refractionTexture = this._getRefractionTexture();
  41042. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41043. defines.REFRACTION = true;
  41044. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41045. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41046. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41047. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41048. if (this._linkRefractionWithTransparency) {
  41049. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41050. }
  41051. }
  41052. else {
  41053. defines.REFRACTION = false;
  41054. }
  41055. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41056. defines.ENVIRONMENTBRDF = true;
  41057. }
  41058. else {
  41059. defines.ENVIRONMENTBRDF = false;
  41060. }
  41061. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41062. defines.ALPHAFROMALBEDO = true;
  41063. }
  41064. else {
  41065. defines.ALPHAFROMALBEDO = false;
  41066. }
  41067. }
  41068. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41069. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41070. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41071. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41072. defines.METALLICWORKFLOW = true;
  41073. }
  41074. else {
  41075. defines.METALLICWORKFLOW = false;
  41076. }
  41077. if (!this.backFaceCulling && this._twoSidedLighting) {
  41078. defines.TWOSIDEDLIGHTING = true;
  41079. }
  41080. else {
  41081. defines.TWOSIDEDLIGHTING = false;
  41082. }
  41083. defines.ALPHATESTVALUE = this._alphaCutOff;
  41084. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41085. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41086. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41087. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41088. }
  41089. if (defines._areImageProcessingDirty) {
  41090. this._imageProcessingConfiguration.prepareDefines(defines);
  41091. }
  41092. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41093. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41094. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41095. // Misc.
  41096. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41097. // Values that need to be evaluated on every frame
  41098. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41099. // Attribs
  41100. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41101. };
  41102. /**
  41103. * Force shader compilation
  41104. */
  41105. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41106. var _this = this;
  41107. var localOptions = __assign({ clipPlane: false }, options);
  41108. var defines = new PBRMaterialDefines();
  41109. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41110. if (effect.isReady()) {
  41111. if (onCompiled) {
  41112. onCompiled(this);
  41113. }
  41114. }
  41115. else {
  41116. effect.onCompileObservable.add(function () {
  41117. if (onCompiled) {
  41118. onCompiled(_this);
  41119. }
  41120. });
  41121. }
  41122. };
  41123. /**
  41124. * Initializes the uniform buffer layout for the shader.
  41125. */
  41126. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41127. // Order is important !
  41128. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41129. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41130. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41131. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41132. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41133. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41134. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41135. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41136. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41137. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41138. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41139. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41140. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41141. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41142. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41143. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41144. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41145. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41146. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41147. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41148. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41149. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41150. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41151. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41152. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41153. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41154. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41155. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41156. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41157. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41158. this._uniformBuffer.addUniform("pointSize", 1);
  41159. this._uniformBuffer.create();
  41160. };
  41161. /**
  41162. * Unbinds the textures.
  41163. */
  41164. PBRBaseMaterial.prototype.unbind = function () {
  41165. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41166. this._uniformBuffer.setTexture("reflectionSampler", null);
  41167. }
  41168. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41169. this._uniformBuffer.setTexture("refractionSampler", null);
  41170. }
  41171. _super.prototype.unbind.call(this);
  41172. };
  41173. /**
  41174. * Binds the submesh data.
  41175. * @param world - The world matrix.
  41176. * @param mesh - The BJS mesh.
  41177. * @param subMesh - A submesh of the BJS mesh.
  41178. */
  41179. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41180. var scene = this.getScene();
  41181. var defines = subMesh._materialDefines;
  41182. if (!defines) {
  41183. return;
  41184. }
  41185. var effect = subMesh.effect;
  41186. if (!effect) {
  41187. return;
  41188. }
  41189. this._activeEffect = effect;
  41190. // Matrices
  41191. this.bindOnlyWorldMatrix(world);
  41192. // Normal Matrix
  41193. if (defines.OBJECTSPACE_NORMALMAP) {
  41194. world.toNormalMatrix(this._normalMatrix);
  41195. this.bindOnlyNormalMatrix(this._normalMatrix);
  41196. }
  41197. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41198. // Bones
  41199. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41200. var reflectionTexture = null;
  41201. if (mustRebind) {
  41202. this._uniformBuffer.bindToEffect(effect, "Material");
  41203. this.bindViewProjection(effect);
  41204. reflectionTexture = this._getReflectionTexture();
  41205. var refractionTexture = this._getRefractionTexture();
  41206. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41207. // Texture uniforms
  41208. if (scene.texturesEnabled) {
  41209. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41210. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41211. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41212. }
  41213. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41214. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41215. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41216. }
  41217. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41218. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41219. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41220. }
  41221. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41222. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41223. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41224. if (reflectionTexture.boundingBoxSize) {
  41225. var cubeTexture = reflectionTexture;
  41226. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41227. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41228. }
  41229. var polynomials = reflectionTexture.sphericalPolynomial;
  41230. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41231. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41232. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41233. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41234. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41235. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41236. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41237. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41238. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41239. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41240. }
  41241. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41242. }
  41243. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41244. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41245. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41246. }
  41247. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41248. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41249. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41250. }
  41251. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41252. if (this._metallicTexture) {
  41253. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41254. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41255. }
  41256. else if (this._reflectivityTexture) {
  41257. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41258. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41259. }
  41260. if (this._microSurfaceTexture) {
  41261. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41262. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41263. }
  41264. }
  41265. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41266. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41267. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41268. if (scene._mirroredCameraPosition) {
  41269. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41270. }
  41271. else {
  41272. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41273. }
  41274. }
  41275. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41276. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41277. var depth = 1.0;
  41278. if (!refractionTexture.isCube) {
  41279. if (refractionTexture.depth) {
  41280. depth = refractionTexture.depth;
  41281. }
  41282. }
  41283. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41284. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41285. }
  41286. }
  41287. // Point size
  41288. if (this.pointsCloud) {
  41289. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41290. }
  41291. // Colors
  41292. if (defines.METALLICWORKFLOW) {
  41293. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41294. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41295. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41296. }
  41297. else {
  41298. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41299. }
  41300. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41301. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41302. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41303. // Misc
  41304. this._lightingInfos.x = this._directIntensity;
  41305. this._lightingInfos.y = this._emissiveIntensity;
  41306. this._lightingInfos.z = this._environmentIntensity;
  41307. this._lightingInfos.w = this._specularIntensity;
  41308. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41309. }
  41310. // Textures
  41311. if (scene.texturesEnabled) {
  41312. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41313. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41314. }
  41315. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41316. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41317. }
  41318. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41319. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41320. }
  41321. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41322. if (defines.LODBASEDMICROSFURACE) {
  41323. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41324. }
  41325. else {
  41326. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41327. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41328. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41329. }
  41330. }
  41331. if (defines.ENVIRONMENTBRDF) {
  41332. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41333. }
  41334. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41335. if (defines.LODBASEDMICROSFURACE) {
  41336. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41337. }
  41338. else {
  41339. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41340. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41341. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41342. }
  41343. }
  41344. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41345. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41346. }
  41347. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41348. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41349. }
  41350. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41351. if (this._metallicTexture) {
  41352. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41353. }
  41354. else if (this._reflectivityTexture) {
  41355. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41356. }
  41357. if (this._microSurfaceTexture) {
  41358. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41359. }
  41360. }
  41361. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41362. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41363. }
  41364. }
  41365. // Clip plane
  41366. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41367. // Colors
  41368. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41369. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41370. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41371. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41372. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41373. }
  41374. if (mustRebind || !this.isFrozen) {
  41375. // Lights
  41376. if (scene.lightsEnabled && !this._disableLighting) {
  41377. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41378. }
  41379. // View
  41380. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41381. this.bindView(effect);
  41382. }
  41383. // Fog
  41384. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41385. // Morph targets
  41386. if (defines.NUM_MORPH_INFLUENCERS) {
  41387. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41388. }
  41389. // image processing
  41390. this._imageProcessingConfiguration.bind(this._activeEffect);
  41391. // Log. depth
  41392. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41393. }
  41394. this._uniformBuffer.update();
  41395. this._afterBind(mesh);
  41396. };
  41397. /**
  41398. * Returns the animatable textures.
  41399. * @returns - Array of animatable textures.
  41400. */
  41401. PBRBaseMaterial.prototype.getAnimatables = function () {
  41402. var results = [];
  41403. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41404. results.push(this._albedoTexture);
  41405. }
  41406. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41407. results.push(this._ambientTexture);
  41408. }
  41409. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41410. results.push(this._opacityTexture);
  41411. }
  41412. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41413. results.push(this._reflectionTexture);
  41414. }
  41415. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41416. results.push(this._emissiveTexture);
  41417. }
  41418. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41419. results.push(this._metallicTexture);
  41420. }
  41421. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41422. results.push(this._reflectivityTexture);
  41423. }
  41424. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41425. results.push(this._bumpTexture);
  41426. }
  41427. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41428. results.push(this._lightmapTexture);
  41429. }
  41430. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41431. results.push(this._refractionTexture);
  41432. }
  41433. return results;
  41434. };
  41435. /**
  41436. * Returns the texture used for reflections.
  41437. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41438. */
  41439. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41440. if (this._reflectionTexture) {
  41441. return this._reflectionTexture;
  41442. }
  41443. return this.getScene().environmentTexture;
  41444. };
  41445. /**
  41446. * Returns the texture used for refraction or null if none is used.
  41447. * @returns - Refection texture if present. If no refraction texture and refraction
  41448. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41449. */
  41450. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41451. if (this._refractionTexture) {
  41452. return this._refractionTexture;
  41453. }
  41454. if (this._linkRefractionWithTransparency) {
  41455. return this.getScene().environmentTexture;
  41456. }
  41457. return null;
  41458. };
  41459. /**
  41460. * Disposes the resources of the material.
  41461. * @param forceDisposeEffect - Forces the disposal of effects.
  41462. * @param forceDisposeTextures - Forces the disposal of all textures.
  41463. */
  41464. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41465. if (forceDisposeTextures) {
  41466. if (this._albedoTexture) {
  41467. this._albedoTexture.dispose();
  41468. }
  41469. if (this._ambientTexture) {
  41470. this._ambientTexture.dispose();
  41471. }
  41472. if (this._opacityTexture) {
  41473. this._opacityTexture.dispose();
  41474. }
  41475. if (this._reflectionTexture) {
  41476. this._reflectionTexture.dispose();
  41477. }
  41478. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41479. this._environmentBRDFTexture.dispose();
  41480. }
  41481. if (this._emissiveTexture) {
  41482. this._emissiveTexture.dispose();
  41483. }
  41484. if (this._metallicTexture) {
  41485. this._metallicTexture.dispose();
  41486. }
  41487. if (this._reflectivityTexture) {
  41488. this._reflectivityTexture.dispose();
  41489. }
  41490. if (this._bumpTexture) {
  41491. this._bumpTexture.dispose();
  41492. }
  41493. if (this._lightmapTexture) {
  41494. this._lightmapTexture.dispose();
  41495. }
  41496. if (this._refractionTexture) {
  41497. this._refractionTexture.dispose();
  41498. }
  41499. }
  41500. this._renderTargets.dispose();
  41501. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41502. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41503. }
  41504. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41505. };
  41506. /**
  41507. * Stores the reflectivity values based on metallic roughness workflow.
  41508. */
  41509. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41510. __decorate([
  41511. BABYLON.serializeAsImageProcessingConfiguration()
  41512. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41513. __decorate([
  41514. BABYLON.serialize()
  41515. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41516. __decorate([
  41517. BABYLON.serialize()
  41518. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41519. return PBRBaseMaterial;
  41520. }(BABYLON.PushMaterial));
  41521. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41522. })(BABYLON || (BABYLON = {}));
  41523. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41524. var BABYLON;
  41525. (function (BABYLON) {
  41526. /**
  41527. * The Physically based simple base material of BJS.
  41528. *
  41529. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41530. * It is used as the base class for both the specGloss and metalRough conventions.
  41531. */
  41532. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41533. __extends(PBRBaseSimpleMaterial, _super);
  41534. /**
  41535. * Instantiates a new PBRMaterial instance.
  41536. *
  41537. * @param name The material name
  41538. * @param scene The scene the material will be use in.
  41539. */
  41540. function PBRBaseSimpleMaterial(name, scene) {
  41541. var _this = _super.call(this, name, scene) || this;
  41542. /**
  41543. * Number of Simultaneous lights allowed on the material.
  41544. */
  41545. _this.maxSimultaneousLights = 4;
  41546. /**
  41547. * If sets to true, disables all the lights affecting the material.
  41548. */
  41549. _this.disableLighting = false;
  41550. /**
  41551. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41552. */
  41553. _this.invertNormalMapX = false;
  41554. /**
  41555. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41556. */
  41557. _this.invertNormalMapY = false;
  41558. /**
  41559. * Emissivie color used to self-illuminate the model.
  41560. */
  41561. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41562. /**
  41563. * Occlusion Channel Strenght.
  41564. */
  41565. _this.occlusionStrength = 1.0;
  41566. _this.useLightmapAsShadowmap = false;
  41567. _this._useAlphaFromAlbedoTexture = true;
  41568. _this._useAmbientInGrayScale = true;
  41569. return _this;
  41570. }
  41571. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41572. /**
  41573. * Gets the current double sided mode.
  41574. */
  41575. get: function () {
  41576. return this._twoSidedLighting;
  41577. },
  41578. /**
  41579. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41580. */
  41581. set: function (value) {
  41582. if (this._twoSidedLighting === value) {
  41583. return;
  41584. }
  41585. this._twoSidedLighting = value;
  41586. this.backFaceCulling = !value;
  41587. this._markAllSubMeshesAsTexturesDirty();
  41588. },
  41589. enumerable: true,
  41590. configurable: true
  41591. });
  41592. /**
  41593. * Return the active textures of the material.
  41594. */
  41595. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41596. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41597. if (this.environmentTexture) {
  41598. activeTextures.push(this.environmentTexture);
  41599. }
  41600. if (this.normalTexture) {
  41601. activeTextures.push(this.normalTexture);
  41602. }
  41603. if (this.emissiveTexture) {
  41604. activeTextures.push(this.emissiveTexture);
  41605. }
  41606. if (this.occlusionTexture) {
  41607. activeTextures.push(this.occlusionTexture);
  41608. }
  41609. if (this.lightmapTexture) {
  41610. activeTextures.push(this.lightmapTexture);
  41611. }
  41612. return activeTextures;
  41613. };
  41614. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41615. if (_super.prototype.hasTexture.call(this, texture)) {
  41616. return true;
  41617. }
  41618. if (this.lightmapTexture === texture) {
  41619. return true;
  41620. }
  41621. return false;
  41622. };
  41623. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41624. return "PBRBaseSimpleMaterial";
  41625. };
  41626. __decorate([
  41627. BABYLON.serialize(),
  41628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41629. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41630. __decorate([
  41631. BABYLON.serialize(),
  41632. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41633. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41634. __decorate([
  41635. BABYLON.serializeAsTexture(),
  41636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41637. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41638. __decorate([
  41639. BABYLON.serialize(),
  41640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41641. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41642. __decorate([
  41643. BABYLON.serialize(),
  41644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41645. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41646. __decorate([
  41647. BABYLON.serializeAsTexture(),
  41648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41649. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41650. __decorate([
  41651. BABYLON.serializeAsColor3("emissive"),
  41652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41653. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41654. __decorate([
  41655. BABYLON.serializeAsTexture(),
  41656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41657. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41658. __decorate([
  41659. BABYLON.serialize(),
  41660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41661. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41662. __decorate([
  41663. BABYLON.serializeAsTexture(),
  41664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41665. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41666. __decorate([
  41667. BABYLON.serialize(),
  41668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41669. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41670. __decorate([
  41671. BABYLON.serialize()
  41672. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41673. __decorate([
  41674. BABYLON.serializeAsTexture(),
  41675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41676. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41677. __decorate([
  41678. BABYLON.serialize(),
  41679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41680. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41681. return PBRBaseSimpleMaterial;
  41682. }(BABYLON.PBRBaseMaterial));
  41683. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41684. })(BABYLON || (BABYLON = {}));
  41685. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41686. var BABYLON;
  41687. (function (BABYLON) {
  41688. /**
  41689. * The Physically based material of BJS.
  41690. *
  41691. * This offers the main features of a standard PBR material.
  41692. * For more information, please refer to the documentation :
  41693. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41694. */
  41695. var PBRMaterial = /** @class */ (function (_super) {
  41696. __extends(PBRMaterial, _super);
  41697. /**
  41698. * Instantiates a new PBRMaterial instance.
  41699. *
  41700. * @param name The material name
  41701. * @param scene The scene the material will be use in.
  41702. */
  41703. function PBRMaterial(name, scene) {
  41704. var _this = _super.call(this, name, scene) || this;
  41705. /**
  41706. * Intensity of the direct lights e.g. the four lights available in your scene.
  41707. * This impacts both the direct diffuse and specular highlights.
  41708. */
  41709. _this.directIntensity = 1.0;
  41710. /**
  41711. * Intensity of the emissive part of the material.
  41712. * This helps controlling the emissive effect without modifying the emissive color.
  41713. */
  41714. _this.emissiveIntensity = 1.0;
  41715. /**
  41716. * Intensity of the environment e.g. how much the environment will light the object
  41717. * either through harmonics for rough material or through the refelction for shiny ones.
  41718. */
  41719. _this.environmentIntensity = 1.0;
  41720. /**
  41721. * This is a special control allowing the reduction of the specular highlights coming from the
  41722. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41723. */
  41724. _this.specularIntensity = 1.0;
  41725. /**
  41726. * Debug Control allowing disabling the bump map on this material.
  41727. */
  41728. _this.disableBumpMap = false;
  41729. /**
  41730. * AKA Occlusion Texture Intensity in other nomenclature.
  41731. */
  41732. _this.ambientTextureStrength = 1.0;
  41733. /**
  41734. * The color of a material in ambient lighting.
  41735. */
  41736. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41737. /**
  41738. * AKA Diffuse Color in other nomenclature.
  41739. */
  41740. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41741. /**
  41742. * AKA Specular Color in other nomenclature.
  41743. */
  41744. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41745. /**
  41746. * The color reflected from the material.
  41747. */
  41748. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41749. /**
  41750. * The color emitted from the material.
  41751. */
  41752. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41753. /**
  41754. * AKA Glossiness in other nomenclature.
  41755. */
  41756. _this.microSurface = 1.0;
  41757. /**
  41758. * source material index of refraction (IOR)' / 'destination material IOR.
  41759. */
  41760. _this.indexOfRefraction = 0.66;
  41761. /**
  41762. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41763. */
  41764. _this.invertRefractionY = false;
  41765. /**
  41766. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41767. * Materials half opaque for instance using refraction could benefit from this control.
  41768. */
  41769. _this.linkRefractionWithTransparency = false;
  41770. _this.useLightmapAsShadowmap = false;
  41771. /**
  41772. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41773. */
  41774. _this.useAlphaFromAlbedoTexture = false;
  41775. /**
  41776. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41777. */
  41778. _this.forceAlphaTest = false;
  41779. /**
  41780. * Defines the alpha limits in alpha test mode.
  41781. */
  41782. _this.alphaCutOff = 0.4;
  41783. /**
  41784. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41785. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41786. */
  41787. _this.useSpecularOverAlpha = true;
  41788. /**
  41789. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41790. */
  41791. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41792. /**
  41793. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41794. */
  41795. _this.useRoughnessFromMetallicTextureAlpha = true;
  41796. /**
  41797. * Specifies if the metallic texture contains the roughness information in its green channel.
  41798. */
  41799. _this.useRoughnessFromMetallicTextureGreen = false;
  41800. /**
  41801. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41802. */
  41803. _this.useMetallnessFromMetallicTextureBlue = false;
  41804. /**
  41805. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41806. */
  41807. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41808. /**
  41809. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41810. */
  41811. _this.useAmbientInGrayScale = false;
  41812. /**
  41813. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41814. * The material will try to infer what glossiness each pixel should be.
  41815. */
  41816. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41817. /**
  41818. * BJS is using an harcoded light falloff based on a manually sets up range.
  41819. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41820. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41821. */
  41822. _this.usePhysicalLightFalloff = true;
  41823. /**
  41824. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41825. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41826. */
  41827. _this.useRadianceOverAlpha = true;
  41828. /**
  41829. * Allows using an object space normal map (instead of tangent space).
  41830. */
  41831. _this.useObjectSpaceNormalMap = false;
  41832. /**
  41833. * Allows using the bump map in parallax mode.
  41834. */
  41835. _this.useParallax = false;
  41836. /**
  41837. * Allows using the bump map in parallax occlusion mode.
  41838. */
  41839. _this.useParallaxOcclusion = false;
  41840. /**
  41841. * Controls the scale bias of the parallax mode.
  41842. */
  41843. _this.parallaxScaleBias = 0.05;
  41844. /**
  41845. * If sets to true, disables all the lights affecting the material.
  41846. */
  41847. _this.disableLighting = false;
  41848. /**
  41849. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41850. */
  41851. _this.forceIrradianceInFragment = false;
  41852. /**
  41853. * Number of Simultaneous lights allowed on the material.
  41854. */
  41855. _this.maxSimultaneousLights = 4;
  41856. /**
  41857. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41858. */
  41859. _this.invertNormalMapX = false;
  41860. /**
  41861. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41862. */
  41863. _this.invertNormalMapY = false;
  41864. /**
  41865. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41866. */
  41867. _this.twoSidedLighting = false;
  41868. /**
  41869. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41870. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41871. */
  41872. _this.useAlphaFresnel = false;
  41873. /**
  41874. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41875. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41876. */
  41877. _this.useLinearAlphaFresnel = false;
  41878. /**
  41879. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41880. * And/Or occlude the blended part.
  41881. */
  41882. _this.environmentBRDFTexture = null;
  41883. /**
  41884. * Force normal to face away from face.
  41885. */
  41886. _this.forceNormalForward = false;
  41887. /**
  41888. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41889. * makes the reflect vector face the model (under horizon).
  41890. */
  41891. _this.useHorizonOcclusion = true;
  41892. /**
  41893. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41894. * too much the area relying on ambient texture to define their ambient occlusion.
  41895. */
  41896. _this.useRadianceOcclusion = true;
  41897. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41898. return _this;
  41899. }
  41900. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41901. /**
  41902. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41903. */
  41904. get: function () {
  41905. return this._PBRMATERIAL_OPAQUE;
  41906. },
  41907. enumerable: true,
  41908. configurable: true
  41909. });
  41910. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41911. /**
  41912. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41913. */
  41914. get: function () {
  41915. return this._PBRMATERIAL_ALPHATEST;
  41916. },
  41917. enumerable: true,
  41918. configurable: true
  41919. });
  41920. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41921. /**
  41922. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41923. */
  41924. get: function () {
  41925. return this._PBRMATERIAL_ALPHABLEND;
  41926. },
  41927. enumerable: true,
  41928. configurable: true
  41929. });
  41930. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41931. /**
  41932. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41933. * They are also discarded below the alpha cutoff threshold to improve performances.
  41934. */
  41935. get: function () {
  41936. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41937. },
  41938. enumerable: true,
  41939. configurable: true
  41940. });
  41941. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41942. /**
  41943. * Gets the image processing configuration used either in this material.
  41944. */
  41945. get: function () {
  41946. return this._imageProcessingConfiguration;
  41947. },
  41948. /**
  41949. * Sets the Default image processing configuration used either in the this material.
  41950. *
  41951. * If sets to null, the scene one is in use.
  41952. */
  41953. set: function (value) {
  41954. this._attachImageProcessingConfiguration(value);
  41955. // Ensure the effect will be rebuilt.
  41956. this._markAllSubMeshesAsTexturesDirty();
  41957. },
  41958. enumerable: true,
  41959. configurable: true
  41960. });
  41961. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41962. /**
  41963. * Gets wether the color curves effect is enabled.
  41964. */
  41965. get: function () {
  41966. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41967. },
  41968. /**
  41969. * Sets wether the color curves effect is enabled.
  41970. */
  41971. set: function (value) {
  41972. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41973. },
  41974. enumerable: true,
  41975. configurable: true
  41976. });
  41977. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41978. /**
  41979. * Gets wether the color grading effect is enabled.
  41980. */
  41981. get: function () {
  41982. return this.imageProcessingConfiguration.colorGradingEnabled;
  41983. },
  41984. /**
  41985. * Gets wether the color grading effect is enabled.
  41986. */
  41987. set: function (value) {
  41988. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41989. },
  41990. enumerable: true,
  41991. configurable: true
  41992. });
  41993. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41994. /**
  41995. * Gets wether tonemapping is enabled or not.
  41996. */
  41997. get: function () {
  41998. return this._imageProcessingConfiguration.toneMappingEnabled;
  41999. },
  42000. /**
  42001. * Sets wether tonemapping is enabled or not
  42002. */
  42003. set: function (value) {
  42004. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42005. },
  42006. enumerable: true,
  42007. configurable: true
  42008. });
  42009. ;
  42010. ;
  42011. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42012. /**
  42013. * The camera exposure used on this material.
  42014. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42015. * This corresponds to a photographic exposure.
  42016. */
  42017. get: function () {
  42018. return this._imageProcessingConfiguration.exposure;
  42019. },
  42020. /**
  42021. * The camera exposure used on this material.
  42022. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42023. * This corresponds to a photographic exposure.
  42024. */
  42025. set: function (value) {
  42026. this._imageProcessingConfiguration.exposure = value;
  42027. },
  42028. enumerable: true,
  42029. configurable: true
  42030. });
  42031. ;
  42032. ;
  42033. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42034. /**
  42035. * Gets The camera contrast used on this material.
  42036. */
  42037. get: function () {
  42038. return this._imageProcessingConfiguration.contrast;
  42039. },
  42040. /**
  42041. * Sets The camera contrast used on this material.
  42042. */
  42043. set: function (value) {
  42044. this._imageProcessingConfiguration.contrast = value;
  42045. },
  42046. enumerable: true,
  42047. configurable: true
  42048. });
  42049. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42050. /**
  42051. * Gets the Color Grading 2D Lookup Texture.
  42052. */
  42053. get: function () {
  42054. return this._imageProcessingConfiguration.colorGradingTexture;
  42055. },
  42056. /**
  42057. * Sets the Color Grading 2D Lookup Texture.
  42058. */
  42059. set: function (value) {
  42060. this._imageProcessingConfiguration.colorGradingTexture = value;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42066. /**
  42067. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42068. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42069. * 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;
  42070. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42071. */
  42072. get: function () {
  42073. return this._imageProcessingConfiguration.colorCurves;
  42074. },
  42075. /**
  42076. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42077. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42078. * 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;
  42079. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42080. */
  42081. set: function (value) {
  42082. this._imageProcessingConfiguration.colorCurves = value;
  42083. },
  42084. enumerable: true,
  42085. configurable: true
  42086. });
  42087. /**
  42088. * Returns the name of this material class.
  42089. */
  42090. PBRMaterial.prototype.getClassName = function () {
  42091. return "PBRMaterial";
  42092. };
  42093. /**
  42094. * Returns an array of the actively used textures.
  42095. * @returns - Array of BaseTextures
  42096. */
  42097. PBRMaterial.prototype.getActiveTextures = function () {
  42098. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42099. if (this._albedoTexture) {
  42100. activeTextures.push(this._albedoTexture);
  42101. }
  42102. if (this._ambientTexture) {
  42103. activeTextures.push(this._ambientTexture);
  42104. }
  42105. if (this._opacityTexture) {
  42106. activeTextures.push(this._opacityTexture);
  42107. }
  42108. if (this._reflectionTexture) {
  42109. activeTextures.push(this._reflectionTexture);
  42110. }
  42111. if (this._emissiveTexture) {
  42112. activeTextures.push(this._emissiveTexture);
  42113. }
  42114. if (this._reflectivityTexture) {
  42115. activeTextures.push(this._reflectivityTexture);
  42116. }
  42117. if (this._metallicTexture) {
  42118. activeTextures.push(this._metallicTexture);
  42119. }
  42120. if (this._microSurfaceTexture) {
  42121. activeTextures.push(this._microSurfaceTexture);
  42122. }
  42123. if (this._bumpTexture) {
  42124. activeTextures.push(this._bumpTexture);
  42125. }
  42126. if (this._lightmapTexture) {
  42127. activeTextures.push(this._lightmapTexture);
  42128. }
  42129. if (this._refractionTexture) {
  42130. activeTextures.push(this._refractionTexture);
  42131. }
  42132. return activeTextures;
  42133. };
  42134. /**
  42135. * Checks to see if a texture is used in the material.
  42136. * @param texture - Base texture to use.
  42137. * @returns - Boolean specifying if a texture is used in the material.
  42138. */
  42139. PBRMaterial.prototype.hasTexture = function (texture) {
  42140. if (_super.prototype.hasTexture.call(this, texture)) {
  42141. return true;
  42142. }
  42143. if (this._albedoTexture === texture) {
  42144. return true;
  42145. }
  42146. if (this._ambientTexture === texture) {
  42147. return true;
  42148. }
  42149. if (this._opacityTexture === texture) {
  42150. return true;
  42151. }
  42152. if (this._reflectionTexture === texture) {
  42153. return true;
  42154. }
  42155. if (this._reflectivityTexture === texture) {
  42156. return true;
  42157. }
  42158. if (this._metallicTexture === texture) {
  42159. return true;
  42160. }
  42161. if (this._microSurfaceTexture === texture) {
  42162. return true;
  42163. }
  42164. if (this._bumpTexture === texture) {
  42165. return true;
  42166. }
  42167. if (this._lightmapTexture === texture) {
  42168. return true;
  42169. }
  42170. if (this._refractionTexture === texture) {
  42171. return true;
  42172. }
  42173. return false;
  42174. };
  42175. /**
  42176. * Makes a duplicate of the current material.
  42177. * @param name - name to use for the new material.
  42178. */
  42179. PBRMaterial.prototype.clone = function (name) {
  42180. var _this = this;
  42181. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42182. clone.id = name;
  42183. clone.name = name;
  42184. return clone;
  42185. };
  42186. /**
  42187. * Serializes this PBR Material.
  42188. * @returns - An object with the serialized material.
  42189. */
  42190. PBRMaterial.prototype.serialize = function () {
  42191. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42192. serializationObject.customType = "BABYLON.PBRMaterial";
  42193. return serializationObject;
  42194. };
  42195. // Statics
  42196. /**
  42197. * Parses a PBR Material from a serialized object.
  42198. * @param source - Serialized object.
  42199. * @param scene - BJS scene instance.
  42200. * @param rootUrl - url for the scene object
  42201. * @returns - PBRMaterial
  42202. */
  42203. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42204. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42205. };
  42206. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42207. /**
  42208. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42209. */
  42210. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42211. /**
  42212. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42213. */
  42214. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42215. /**
  42216. * 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.
  42217. * They are also discarded below the alpha cutoff threshold to improve performances.
  42218. */
  42219. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42220. __decorate([
  42221. BABYLON.serialize(),
  42222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42223. ], PBRMaterial.prototype, "directIntensity", void 0);
  42224. __decorate([
  42225. BABYLON.serialize(),
  42226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42227. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42228. __decorate([
  42229. BABYLON.serialize(),
  42230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42231. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42232. __decorate([
  42233. BABYLON.serialize(),
  42234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42235. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42236. __decorate([
  42237. BABYLON.serialize(),
  42238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42239. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42240. __decorate([
  42241. BABYLON.serializeAsTexture(),
  42242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42243. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42244. __decorate([
  42245. BABYLON.serializeAsTexture(),
  42246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42247. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42248. __decorate([
  42249. BABYLON.serialize(),
  42250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42251. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42252. __decorate([
  42253. BABYLON.serializeAsTexture(),
  42254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42255. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42256. __decorate([
  42257. BABYLON.serializeAsTexture(),
  42258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42259. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42260. __decorate([
  42261. BABYLON.serializeAsTexture(),
  42262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42263. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42264. __decorate([
  42265. BABYLON.serializeAsTexture(),
  42266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42267. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42268. __decorate([
  42269. BABYLON.serializeAsTexture(),
  42270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42271. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42272. __decorate([
  42273. BABYLON.serialize(),
  42274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42275. ], PBRMaterial.prototype, "metallic", void 0);
  42276. __decorate([
  42277. BABYLON.serialize(),
  42278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42279. ], PBRMaterial.prototype, "roughness", void 0);
  42280. __decorate([
  42281. BABYLON.serializeAsTexture(),
  42282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42283. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42284. __decorate([
  42285. BABYLON.serializeAsTexture(),
  42286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42287. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42288. __decorate([
  42289. BABYLON.serializeAsTexture(),
  42290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42291. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42292. __decorate([
  42293. BABYLON.serializeAsTexture(),
  42294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42295. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42296. __decorate([
  42297. BABYLON.serializeAsColor3("ambient"),
  42298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42299. ], PBRMaterial.prototype, "ambientColor", void 0);
  42300. __decorate([
  42301. BABYLON.serializeAsColor3("albedo"),
  42302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42303. ], PBRMaterial.prototype, "albedoColor", void 0);
  42304. __decorate([
  42305. BABYLON.serializeAsColor3("reflectivity"),
  42306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42307. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42308. __decorate([
  42309. BABYLON.serializeAsColor3("reflection"),
  42310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42311. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42312. __decorate([
  42313. BABYLON.serializeAsColor3("emissive"),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42315. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42316. __decorate([
  42317. BABYLON.serialize(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42319. ], PBRMaterial.prototype, "microSurface", void 0);
  42320. __decorate([
  42321. BABYLON.serialize(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42323. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42324. __decorate([
  42325. BABYLON.serialize(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42328. __decorate([
  42329. BABYLON.serialize(),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42332. __decorate([
  42333. BABYLON.serialize(),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42335. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42336. __decorate([
  42337. BABYLON.serialize(),
  42338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42339. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42340. __decorate([
  42341. BABYLON.serialize(),
  42342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42343. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42344. __decorate([
  42345. BABYLON.serialize(),
  42346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42347. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42348. __decorate([
  42349. BABYLON.serialize(),
  42350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42351. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42352. __decorate([
  42353. BABYLON.serialize(),
  42354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42355. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42356. __decorate([
  42357. BABYLON.serialize(),
  42358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42359. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42360. __decorate([
  42361. BABYLON.serialize(),
  42362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42363. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42364. __decorate([
  42365. BABYLON.serialize(),
  42366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42367. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42368. __decorate([
  42369. BABYLON.serialize(),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42371. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42372. __decorate([
  42373. BABYLON.serialize(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42375. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42376. __decorate([
  42377. BABYLON.serialize(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42379. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42380. __decorate([
  42381. BABYLON.serialize(),
  42382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42383. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42384. __decorate([
  42385. BABYLON.serialize(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42387. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42388. __decorate([
  42389. BABYLON.serialize(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42391. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42392. __decorate([
  42393. BABYLON.serialize(),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42395. ], PBRMaterial.prototype, "useParallax", void 0);
  42396. __decorate([
  42397. BABYLON.serialize(),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42403. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42404. __decorate([
  42405. BABYLON.serialize(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42407. ], PBRMaterial.prototype, "disableLighting", void 0);
  42408. __decorate([
  42409. BABYLON.serialize(),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42411. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42412. __decorate([
  42413. BABYLON.serialize(),
  42414. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42415. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42416. __decorate([
  42417. BABYLON.serialize(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42419. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42420. __decorate([
  42421. BABYLON.serialize(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42423. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42424. __decorate([
  42425. BABYLON.serialize(),
  42426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42427. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42428. __decorate([
  42429. BABYLON.serialize(),
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42431. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42432. __decorate([
  42433. BABYLON.serialize(),
  42434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42435. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42436. __decorate([
  42437. BABYLON.serializeAsTexture(),
  42438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42439. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42440. __decorate([
  42441. BABYLON.serialize(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42447. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42448. __decorate([
  42449. BABYLON.serialize(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42451. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42452. return PBRMaterial;
  42453. }(BABYLON.PBRBaseMaterial));
  42454. BABYLON.PBRMaterial = PBRMaterial;
  42455. })(BABYLON || (BABYLON = {}));
  42456. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42457. var BABYLON;
  42458. (function (BABYLON) {
  42459. /**
  42460. * The PBR material of BJS following the metal roughness convention.
  42461. *
  42462. * This fits to the PBR convention in the GLTF definition:
  42463. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42464. */
  42465. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42466. __extends(PBRMetallicRoughnessMaterial, _super);
  42467. /**
  42468. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42469. *
  42470. * @param name The material name
  42471. * @param scene The scene the material will be use in.
  42472. */
  42473. function PBRMetallicRoughnessMaterial(name, scene) {
  42474. var _this = _super.call(this, name, scene) || this;
  42475. _this._useRoughnessFromMetallicTextureAlpha = false;
  42476. _this._useRoughnessFromMetallicTextureGreen = true;
  42477. _this._useMetallnessFromMetallicTextureBlue = true;
  42478. _this._forceMetallicWorkflow = true;
  42479. return _this;
  42480. }
  42481. /**
  42482. * Return the currrent class name of the material.
  42483. */
  42484. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42485. return "PBRMetallicRoughnessMaterial";
  42486. };
  42487. /**
  42488. * Return the active textures of the material.
  42489. */
  42490. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42491. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42492. if (this.baseTexture) {
  42493. activeTextures.push(this.baseTexture);
  42494. }
  42495. if (this.metallicRoughnessTexture) {
  42496. activeTextures.push(this.metallicRoughnessTexture);
  42497. }
  42498. return activeTextures;
  42499. };
  42500. /**
  42501. * Checks to see if a texture is used in the material.
  42502. * @param texture - Base texture to use.
  42503. * @returns - Boolean specifying if a texture is used in the material.
  42504. */
  42505. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42506. if (_super.prototype.hasTexture.call(this, texture)) {
  42507. return true;
  42508. }
  42509. if (this.baseTexture === texture) {
  42510. return true;
  42511. }
  42512. if (this.metallicRoughnessTexture === texture) {
  42513. return true;
  42514. }
  42515. return false;
  42516. };
  42517. /**
  42518. * Makes a duplicate of the current material.
  42519. * @param name - name to use for the new material.
  42520. */
  42521. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42522. var _this = this;
  42523. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42524. clone.id = name;
  42525. clone.name = name;
  42526. return clone;
  42527. };
  42528. /**
  42529. * Serialize the material to a parsable JSON object.
  42530. */
  42531. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42532. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42533. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42534. return serializationObject;
  42535. };
  42536. /**
  42537. * Parses a JSON object correponding to the serialize function.
  42538. */
  42539. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42540. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42541. };
  42542. __decorate([
  42543. BABYLON.serializeAsColor3(),
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42545. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42546. __decorate([
  42547. BABYLON.serializeAsTexture(),
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42549. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42550. __decorate([
  42551. BABYLON.serialize(),
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42554. __decorate([
  42555. BABYLON.serialize(),
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42557. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42558. __decorate([
  42559. BABYLON.serializeAsTexture(),
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42561. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42562. return PBRMetallicRoughnessMaterial;
  42563. }(BABYLON.PBRBaseSimpleMaterial));
  42564. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42565. })(BABYLON || (BABYLON = {}));
  42566. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42567. var BABYLON;
  42568. (function (BABYLON) {
  42569. /**
  42570. * The PBR material of BJS following the specular glossiness convention.
  42571. *
  42572. * This fits to the PBR convention in the GLTF definition:
  42573. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42574. */
  42575. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42576. __extends(PBRSpecularGlossinessMaterial, _super);
  42577. /**
  42578. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42579. *
  42580. * @param name The material name
  42581. * @param scene The scene the material will be use in.
  42582. */
  42583. function PBRSpecularGlossinessMaterial(name, scene) {
  42584. var _this = _super.call(this, name, scene) || this;
  42585. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42586. return _this;
  42587. }
  42588. /**
  42589. * Return the currrent class name of the material.
  42590. */
  42591. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42592. return "PBRSpecularGlossinessMaterial";
  42593. };
  42594. /**
  42595. * Return the active textures of the material.
  42596. */
  42597. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42598. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42599. if (this.diffuseTexture) {
  42600. activeTextures.push(this.diffuseTexture);
  42601. }
  42602. if (this.specularGlossinessTexture) {
  42603. activeTextures.push(this.specularGlossinessTexture);
  42604. }
  42605. return activeTextures;
  42606. };
  42607. /**
  42608. * Checks to see if a texture is used in the material.
  42609. * @param texture - Base texture to use.
  42610. * @returns - Boolean specifying if a texture is used in the material.
  42611. */
  42612. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42613. if (_super.prototype.hasTexture.call(this, texture)) {
  42614. return true;
  42615. }
  42616. if (this.diffuseTexture === texture) {
  42617. return true;
  42618. }
  42619. if (this.specularGlossinessTexture === texture) {
  42620. return true;
  42621. }
  42622. return false;
  42623. };
  42624. /**
  42625. * Makes a duplicate of the current material.
  42626. * @param name - name to use for the new material.
  42627. */
  42628. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42629. var _this = this;
  42630. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42631. clone.id = name;
  42632. clone.name = name;
  42633. return clone;
  42634. };
  42635. /**
  42636. * Serialize the material to a parsable JSON object.
  42637. */
  42638. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42639. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42640. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42641. return serializationObject;
  42642. };
  42643. /**
  42644. * Parses a JSON object correponding to the serialize function.
  42645. */
  42646. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42647. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42648. };
  42649. __decorate([
  42650. BABYLON.serializeAsColor3("diffuse"),
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42652. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42653. __decorate([
  42654. BABYLON.serializeAsTexture(),
  42655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42656. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42657. __decorate([
  42658. BABYLON.serializeAsColor3("specular"),
  42659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42660. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42661. __decorate([
  42662. BABYLON.serialize(),
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42664. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42665. __decorate([
  42666. BABYLON.serializeAsTexture(),
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42668. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42669. return PBRSpecularGlossinessMaterial;
  42670. }(BABYLON.PBRBaseSimpleMaterial));
  42671. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42672. })(BABYLON || (BABYLON = {}));
  42673. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42674. var BABYLON;
  42675. (function (BABYLON) {
  42676. BABYLON.CameraInputTypes = {};
  42677. var CameraInputsManager = /** @class */ (function () {
  42678. function CameraInputsManager(camera) {
  42679. this.attached = {};
  42680. this.camera = camera;
  42681. this.checkInputs = function () { };
  42682. }
  42683. /**
  42684. * Add an input method to a camera.
  42685. * builtin inputs example: camera.inputs.addGamepad();
  42686. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42687. * @param input camera input method
  42688. */
  42689. CameraInputsManager.prototype.add = function (input) {
  42690. var type = input.getSimpleName();
  42691. if (this.attached[type]) {
  42692. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42693. return;
  42694. }
  42695. this.attached[type] = input;
  42696. input.camera = this.camera;
  42697. //for checkInputs, we are dynamically creating a function
  42698. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42699. if (input.checkInputs) {
  42700. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42701. }
  42702. if (this.attachedElement) {
  42703. input.attachControl(this.attachedElement);
  42704. }
  42705. };
  42706. /**
  42707. * Remove a specific input method from a camera
  42708. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42709. * @param inputToRemove camera input method
  42710. */
  42711. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42712. for (var cam in this.attached) {
  42713. var input = this.attached[cam];
  42714. if (input === inputToRemove) {
  42715. input.detachControl(this.attachedElement);
  42716. input.camera = null;
  42717. delete this.attached[cam];
  42718. this.rebuildInputCheck();
  42719. }
  42720. }
  42721. };
  42722. CameraInputsManager.prototype.removeByType = function (inputType) {
  42723. for (var cam in this.attached) {
  42724. var input = this.attached[cam];
  42725. if (input.getClassName() === inputType) {
  42726. input.detachControl(this.attachedElement);
  42727. input.camera = null;
  42728. delete this.attached[cam];
  42729. this.rebuildInputCheck();
  42730. }
  42731. }
  42732. };
  42733. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42734. var current = this.checkInputs;
  42735. return function () {
  42736. current();
  42737. fn();
  42738. };
  42739. };
  42740. CameraInputsManager.prototype.attachInput = function (input) {
  42741. if (this.attachedElement) {
  42742. input.attachControl(this.attachedElement, this.noPreventDefault);
  42743. }
  42744. };
  42745. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42746. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42747. if (this.attachedElement) {
  42748. return;
  42749. }
  42750. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42751. this.attachedElement = element;
  42752. this.noPreventDefault = noPreventDefault;
  42753. for (var cam in this.attached) {
  42754. this.attached[cam].attachControl(element, noPreventDefault);
  42755. }
  42756. };
  42757. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42758. if (disconnect === void 0) { disconnect = false; }
  42759. if (this.attachedElement !== element) {
  42760. return;
  42761. }
  42762. for (var cam in this.attached) {
  42763. this.attached[cam].detachControl(element);
  42764. if (disconnect) {
  42765. this.attached[cam].camera = null;
  42766. }
  42767. }
  42768. this.attachedElement = null;
  42769. };
  42770. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42771. this.checkInputs = function () { };
  42772. for (var cam in this.attached) {
  42773. var input = this.attached[cam];
  42774. if (input.checkInputs) {
  42775. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42776. }
  42777. }
  42778. };
  42779. /**
  42780. * Remove all attached input methods from a camera
  42781. */
  42782. CameraInputsManager.prototype.clear = function () {
  42783. if (this.attachedElement) {
  42784. this.detachElement(this.attachedElement, true);
  42785. }
  42786. this.attached = {};
  42787. this.attachedElement = null;
  42788. this.checkInputs = function () { };
  42789. };
  42790. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42791. var inputs = {};
  42792. for (var cam in this.attached) {
  42793. var input = this.attached[cam];
  42794. var res = BABYLON.SerializationHelper.Serialize(input);
  42795. inputs[input.getClassName()] = res;
  42796. }
  42797. serializedCamera.inputsmgr = inputs;
  42798. };
  42799. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42800. var parsedInputs = parsedCamera.inputsmgr;
  42801. if (parsedInputs) {
  42802. this.clear();
  42803. for (var n in parsedInputs) {
  42804. var construct = BABYLON.CameraInputTypes[n];
  42805. if (construct) {
  42806. var parsedinput = parsedInputs[n];
  42807. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42808. this.add(input);
  42809. }
  42810. }
  42811. }
  42812. else {
  42813. //2016-03-08 this part is for managing backward compatibility
  42814. for (var n in this.attached) {
  42815. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42816. if (construct) {
  42817. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42818. this.remove(this.attached[n]);
  42819. this.add(input);
  42820. }
  42821. }
  42822. }
  42823. };
  42824. return CameraInputsManager;
  42825. }());
  42826. BABYLON.CameraInputsManager = CameraInputsManager;
  42827. })(BABYLON || (BABYLON = {}));
  42828. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42829. var BABYLON;
  42830. (function (BABYLON) {
  42831. var TargetCamera = /** @class */ (function (_super) {
  42832. __extends(TargetCamera, _super);
  42833. function TargetCamera(name, position, scene) {
  42834. var _this = _super.call(this, name, position, scene) || this;
  42835. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42836. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42837. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42838. _this.speed = 2.0;
  42839. _this.noRotationConstraint = false;
  42840. _this.lockedTarget = null;
  42841. _this._currentTarget = BABYLON.Vector3.Zero();
  42842. _this._viewMatrix = BABYLON.Matrix.Zero();
  42843. _this._camMatrix = BABYLON.Matrix.Zero();
  42844. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42845. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42846. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42847. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42848. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42849. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42850. _this._tempMatrix = BABYLON.Matrix.Zero();
  42851. return _this;
  42852. }
  42853. TargetCamera.prototype.getFrontPosition = function (distance) {
  42854. this.getWorldMatrix();
  42855. var direction = this.getTarget().subtract(this.position);
  42856. direction.normalize();
  42857. direction.scaleInPlace(distance);
  42858. return this.globalPosition.add(direction);
  42859. };
  42860. TargetCamera.prototype._getLockedTargetPosition = function () {
  42861. if (!this.lockedTarget) {
  42862. return null;
  42863. }
  42864. if (this.lockedTarget.absolutePosition) {
  42865. this.lockedTarget.computeWorldMatrix();
  42866. }
  42867. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42868. };
  42869. TargetCamera.prototype.storeState = function () {
  42870. this._storedPosition = this.position.clone();
  42871. this._storedRotation = this.rotation.clone();
  42872. if (this.rotationQuaternion) {
  42873. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42874. }
  42875. return _super.prototype.storeState.call(this);
  42876. };
  42877. /**
  42878. * Restored camera state. You must call storeState() first
  42879. */
  42880. TargetCamera.prototype._restoreStateValues = function () {
  42881. if (!_super.prototype._restoreStateValues.call(this)) {
  42882. return false;
  42883. }
  42884. this.position = this._storedPosition.clone();
  42885. this.rotation = this._storedRotation.clone();
  42886. if (this.rotationQuaternion) {
  42887. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42888. }
  42889. this.cameraDirection.copyFromFloats(0, 0, 0);
  42890. this.cameraRotation.copyFromFloats(0, 0);
  42891. return true;
  42892. };
  42893. // Cache
  42894. TargetCamera.prototype._initCache = function () {
  42895. _super.prototype._initCache.call(this);
  42896. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42897. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42898. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42899. };
  42900. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42901. if (!ignoreParentClass) {
  42902. _super.prototype._updateCache.call(this);
  42903. }
  42904. var lockedTargetPosition = this._getLockedTargetPosition();
  42905. if (!lockedTargetPosition) {
  42906. this._cache.lockedTarget = null;
  42907. }
  42908. else {
  42909. if (!this._cache.lockedTarget) {
  42910. this._cache.lockedTarget = lockedTargetPosition.clone();
  42911. }
  42912. else {
  42913. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42914. }
  42915. }
  42916. this._cache.rotation.copyFrom(this.rotation);
  42917. if (this.rotationQuaternion)
  42918. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42919. };
  42920. // Synchronized
  42921. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42922. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42923. return false;
  42924. }
  42925. var lockedTargetPosition = this._getLockedTargetPosition();
  42926. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42927. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42928. };
  42929. // Methods
  42930. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42931. var engine = this.getEngine();
  42932. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42933. };
  42934. // Target
  42935. TargetCamera.prototype.setTarget = function (target) {
  42936. this.upVector.normalize();
  42937. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42938. this._camMatrix.invert();
  42939. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42940. var vDir = target.subtract(this.position);
  42941. if (vDir.x >= 0.0) {
  42942. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42943. }
  42944. else {
  42945. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42946. }
  42947. this.rotation.z = 0;
  42948. if (isNaN(this.rotation.x)) {
  42949. this.rotation.x = 0;
  42950. }
  42951. if (isNaN(this.rotation.y)) {
  42952. this.rotation.y = 0;
  42953. }
  42954. if (isNaN(this.rotation.z)) {
  42955. this.rotation.z = 0;
  42956. }
  42957. if (this.rotationQuaternion) {
  42958. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42959. }
  42960. };
  42961. /**
  42962. * Return the current target position of the camera. This value is expressed in local space.
  42963. */
  42964. TargetCamera.prototype.getTarget = function () {
  42965. return this._currentTarget;
  42966. };
  42967. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42968. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42969. };
  42970. TargetCamera.prototype._updatePosition = function () {
  42971. if (this.parent) {
  42972. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42973. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42974. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42975. return;
  42976. }
  42977. this.position.addInPlace(this.cameraDirection);
  42978. };
  42979. TargetCamera.prototype._checkInputs = function () {
  42980. var needToMove = this._decideIfNeedsToMove();
  42981. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42982. // Move
  42983. if (needToMove) {
  42984. this._updatePosition();
  42985. }
  42986. // Rotate
  42987. if (needToRotate) {
  42988. this.rotation.x += this.cameraRotation.x;
  42989. this.rotation.y += this.cameraRotation.y;
  42990. //rotate, if quaternion is set and rotation was used
  42991. if (this.rotationQuaternion) {
  42992. var len = this.rotation.lengthSquared();
  42993. if (len) {
  42994. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42995. }
  42996. }
  42997. if (!this.noRotationConstraint) {
  42998. var limit = (Math.PI / 2) * 0.95;
  42999. if (this.rotation.x > limit)
  43000. this.rotation.x = limit;
  43001. if (this.rotation.x < -limit)
  43002. this.rotation.x = -limit;
  43003. }
  43004. }
  43005. // Inertia
  43006. if (needToMove) {
  43007. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43008. this.cameraDirection.x = 0;
  43009. }
  43010. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43011. this.cameraDirection.y = 0;
  43012. }
  43013. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43014. this.cameraDirection.z = 0;
  43015. }
  43016. this.cameraDirection.scaleInPlace(this.inertia);
  43017. }
  43018. if (needToRotate) {
  43019. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43020. this.cameraRotation.x = 0;
  43021. }
  43022. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43023. this.cameraRotation.y = 0;
  43024. }
  43025. this.cameraRotation.scaleInPlace(this.inertia);
  43026. }
  43027. _super.prototype._checkInputs.call(this);
  43028. };
  43029. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43030. if (this.rotationQuaternion) {
  43031. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43032. }
  43033. else {
  43034. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43035. }
  43036. //update the up vector!
  43037. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43038. };
  43039. TargetCamera.prototype._getViewMatrix = function () {
  43040. if (this.lockedTarget) {
  43041. this.setTarget(this._getLockedTargetPosition());
  43042. }
  43043. // Compute
  43044. this._updateCameraRotationMatrix();
  43045. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43046. // Computing target and final matrix
  43047. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43048. if (this.getScene().useRightHandedSystem) {
  43049. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43050. }
  43051. else {
  43052. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43053. }
  43054. return this._viewMatrix;
  43055. };
  43056. /**
  43057. * @override
  43058. * Override Camera.createRigCamera
  43059. */
  43060. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43061. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43062. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43063. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43064. if (!this.rotationQuaternion) {
  43065. this.rotationQuaternion = new BABYLON.Quaternion();
  43066. }
  43067. rigCamera._cameraRigParams = {};
  43068. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43069. }
  43070. return rigCamera;
  43071. }
  43072. return null;
  43073. };
  43074. /**
  43075. * @override
  43076. * Override Camera._updateRigCameras
  43077. */
  43078. TargetCamera.prototype._updateRigCameras = function () {
  43079. var camLeft = this._rigCameras[0];
  43080. var camRight = this._rigCameras[1];
  43081. switch (this.cameraRigMode) {
  43082. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43085. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43086. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43087. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43088. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43089. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43090. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43091. camLeft.setTarget(this.getTarget());
  43092. camRight.setTarget(this.getTarget());
  43093. break;
  43094. case BABYLON.Camera.RIG_MODE_VR:
  43095. if (camLeft.rotationQuaternion) {
  43096. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43097. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43098. }
  43099. else {
  43100. camLeft.rotation.copyFrom(this.rotation);
  43101. camRight.rotation.copyFrom(this.rotation);
  43102. }
  43103. camLeft.position.copyFrom(this.position);
  43104. camRight.position.copyFrom(this.position);
  43105. break;
  43106. }
  43107. _super.prototype._updateRigCameras.call(this);
  43108. };
  43109. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43110. if (!this._rigCamTransformMatrix) {
  43111. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43112. }
  43113. var target = this.getTarget();
  43114. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43115. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43116. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43117. };
  43118. TargetCamera.prototype.getClassName = function () {
  43119. return "TargetCamera";
  43120. };
  43121. __decorate([
  43122. BABYLON.serializeAsVector3()
  43123. ], TargetCamera.prototype, "rotation", void 0);
  43124. __decorate([
  43125. BABYLON.serialize()
  43126. ], TargetCamera.prototype, "speed", void 0);
  43127. __decorate([
  43128. BABYLON.serializeAsMeshReference("lockedTargetId")
  43129. ], TargetCamera.prototype, "lockedTarget", void 0);
  43130. return TargetCamera;
  43131. }(BABYLON.Camera));
  43132. BABYLON.TargetCamera = TargetCamera;
  43133. })(BABYLON || (BABYLON = {}));
  43134. //# sourceMappingURL=babylon.targetCamera.js.map
  43135. var BABYLON;
  43136. (function (BABYLON) {
  43137. var FreeCameraMouseInput = /** @class */ (function () {
  43138. function FreeCameraMouseInput(touchEnabled) {
  43139. if (touchEnabled === void 0) { touchEnabled = true; }
  43140. this.touchEnabled = touchEnabled;
  43141. this.buttons = [0, 1, 2];
  43142. this.angularSensibility = 2000.0;
  43143. this.previousPosition = null;
  43144. }
  43145. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43146. var _this = this;
  43147. var engine = this.camera.getEngine();
  43148. if (!this._pointerInput) {
  43149. this._pointerInput = function (p, s) {
  43150. var evt = p.event;
  43151. if (engine.isInVRExclusivePointerMode) {
  43152. return;
  43153. }
  43154. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43155. return;
  43156. }
  43157. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43158. return;
  43159. }
  43160. var srcElement = (evt.srcElement || evt.target);
  43161. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43162. try {
  43163. srcElement.setPointerCapture(evt.pointerId);
  43164. }
  43165. catch (e) {
  43166. //Nothing to do with the error. Execution will continue.
  43167. }
  43168. _this.previousPosition = {
  43169. x: evt.clientX,
  43170. y: evt.clientY
  43171. };
  43172. if (!noPreventDefault) {
  43173. evt.preventDefault();
  43174. element.focus();
  43175. }
  43176. }
  43177. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43178. try {
  43179. srcElement.releasePointerCapture(evt.pointerId);
  43180. }
  43181. catch (e) {
  43182. //Nothing to do with the error.
  43183. }
  43184. _this.previousPosition = null;
  43185. if (!noPreventDefault) {
  43186. evt.preventDefault();
  43187. }
  43188. }
  43189. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43190. if (!_this.previousPosition || engine.isPointerLock) {
  43191. return;
  43192. }
  43193. var offsetX = evt.clientX - _this.previousPosition.x;
  43194. var offsetY = evt.clientY - _this.previousPosition.y;
  43195. if (_this.camera.getScene().useRightHandedSystem) {
  43196. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43197. }
  43198. else {
  43199. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43200. }
  43201. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43202. _this.previousPosition = {
  43203. x: evt.clientX,
  43204. y: evt.clientY
  43205. };
  43206. if (!noPreventDefault) {
  43207. evt.preventDefault();
  43208. }
  43209. }
  43210. };
  43211. }
  43212. this._onMouseMove = function (evt) {
  43213. if (!engine.isPointerLock) {
  43214. return;
  43215. }
  43216. if (engine.isInVRExclusivePointerMode) {
  43217. return;
  43218. }
  43219. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43220. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43221. if (_this.camera.getScene().useRightHandedSystem) {
  43222. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43223. }
  43224. else {
  43225. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43226. }
  43227. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43228. _this.previousPosition = null;
  43229. if (!noPreventDefault) {
  43230. evt.preventDefault();
  43231. }
  43232. };
  43233. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43234. element.addEventListener("mousemove", this._onMouseMove, false);
  43235. };
  43236. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43237. if (this._observer && element) {
  43238. this.camera.getScene().onPointerObservable.remove(this._observer);
  43239. if (this._onMouseMove) {
  43240. element.removeEventListener("mousemove", this._onMouseMove);
  43241. }
  43242. this._observer = null;
  43243. this._onMouseMove = null;
  43244. this.previousPosition = null;
  43245. }
  43246. };
  43247. FreeCameraMouseInput.prototype.getClassName = function () {
  43248. return "FreeCameraMouseInput";
  43249. };
  43250. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43251. return "mouse";
  43252. };
  43253. __decorate([
  43254. BABYLON.serialize()
  43255. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43256. __decorate([
  43257. BABYLON.serialize()
  43258. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43259. return FreeCameraMouseInput;
  43260. }());
  43261. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43262. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43263. })(BABYLON || (BABYLON = {}));
  43264. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43265. var BABYLON;
  43266. (function (BABYLON) {
  43267. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43268. function FreeCameraKeyboardMoveInput() {
  43269. this._keys = new Array();
  43270. this.keysUp = [38];
  43271. this.keysDown = [40];
  43272. this.keysLeft = [37];
  43273. this.keysRight = [39];
  43274. }
  43275. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43276. var _this = this;
  43277. if (this._onCanvasBlurObserver) {
  43278. return;
  43279. }
  43280. this._scene = this.camera.getScene();
  43281. this._engine = this._scene.getEngine();
  43282. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43283. _this._keys = [];
  43284. });
  43285. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43286. var evt = info.event;
  43287. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43288. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43289. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43290. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43291. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43292. var index = _this._keys.indexOf(evt.keyCode);
  43293. if (index === -1) {
  43294. _this._keys.push(evt.keyCode);
  43295. }
  43296. if (!noPreventDefault) {
  43297. evt.preventDefault();
  43298. }
  43299. }
  43300. }
  43301. else {
  43302. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43303. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43304. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43305. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43306. var index = _this._keys.indexOf(evt.keyCode);
  43307. if (index >= 0) {
  43308. _this._keys.splice(index, 1);
  43309. }
  43310. if (!noPreventDefault) {
  43311. evt.preventDefault();
  43312. }
  43313. }
  43314. }
  43315. });
  43316. };
  43317. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43318. if (this._scene) {
  43319. if (this._onKeyboardObserver) {
  43320. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43321. }
  43322. if (this._onCanvasBlurObserver) {
  43323. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43324. }
  43325. this._onKeyboardObserver = null;
  43326. this._onCanvasBlurObserver = null;
  43327. }
  43328. this._keys = [];
  43329. };
  43330. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43331. if (this._onKeyboardObserver) {
  43332. var camera = this.camera;
  43333. // Keyboard
  43334. for (var index = 0; index < this._keys.length; index++) {
  43335. var keyCode = this._keys[index];
  43336. var speed = camera._computeLocalCameraSpeed();
  43337. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43338. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43339. }
  43340. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43341. camera._localDirection.copyFromFloats(0, 0, speed);
  43342. }
  43343. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43344. camera._localDirection.copyFromFloats(speed, 0, 0);
  43345. }
  43346. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43347. camera._localDirection.copyFromFloats(0, 0, -speed);
  43348. }
  43349. if (camera.getScene().useRightHandedSystem) {
  43350. camera._localDirection.z *= -1;
  43351. }
  43352. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43353. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43354. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43355. }
  43356. }
  43357. };
  43358. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43359. return "FreeCameraKeyboardMoveInput";
  43360. };
  43361. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43362. this._keys = [];
  43363. };
  43364. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43365. return "keyboard";
  43366. };
  43367. __decorate([
  43368. BABYLON.serialize()
  43369. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43370. __decorate([
  43371. BABYLON.serialize()
  43372. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43373. __decorate([
  43374. BABYLON.serialize()
  43375. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43376. __decorate([
  43377. BABYLON.serialize()
  43378. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43379. return FreeCameraKeyboardMoveInput;
  43380. }());
  43381. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43382. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43383. })(BABYLON || (BABYLON = {}));
  43384. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43385. var BABYLON;
  43386. (function (BABYLON) {
  43387. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43388. __extends(FreeCameraInputsManager, _super);
  43389. function FreeCameraInputsManager(camera) {
  43390. return _super.call(this, camera) || this;
  43391. }
  43392. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43393. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43394. return this;
  43395. };
  43396. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43397. if (touchEnabled === void 0) { touchEnabled = true; }
  43398. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43399. return this;
  43400. };
  43401. FreeCameraInputsManager.prototype.addGamepad = function () {
  43402. this.add(new BABYLON.FreeCameraGamepadInput());
  43403. return this;
  43404. };
  43405. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43406. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43407. return this;
  43408. };
  43409. FreeCameraInputsManager.prototype.addTouch = function () {
  43410. this.add(new BABYLON.FreeCameraTouchInput());
  43411. return this;
  43412. };
  43413. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43414. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43415. return this;
  43416. };
  43417. return FreeCameraInputsManager;
  43418. }(BABYLON.CameraInputsManager));
  43419. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43420. })(BABYLON || (BABYLON = {}));
  43421. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43422. var BABYLON;
  43423. (function (BABYLON) {
  43424. var FreeCamera = /** @class */ (function (_super) {
  43425. __extends(FreeCamera, _super);
  43426. function FreeCamera(name, position, scene) {
  43427. var _this = _super.call(this, name, position, scene) || this;
  43428. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43429. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43430. _this.checkCollisions = false;
  43431. _this.applyGravity = false;
  43432. _this._needMoveForGravity = false;
  43433. _this._oldPosition = BABYLON.Vector3.Zero();
  43434. _this._diffPosition = BABYLON.Vector3.Zero();
  43435. _this._newPosition = BABYLON.Vector3.Zero();
  43436. // Collisions
  43437. _this._collisionMask = -1;
  43438. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43439. if (collidedMesh === void 0) { collidedMesh = null; }
  43440. //TODO move this to the collision coordinator!
  43441. if (_this.getScene().workerCollisions)
  43442. newPosition.multiplyInPlace(_this._collider._radius);
  43443. var updatePosition = function (newPos) {
  43444. _this._newPosition.copyFrom(newPos);
  43445. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43446. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43447. _this.position.addInPlace(_this._diffPosition);
  43448. if (_this.onCollide && collidedMesh) {
  43449. _this.onCollide(collidedMesh);
  43450. }
  43451. }
  43452. };
  43453. updatePosition(newPosition);
  43454. };
  43455. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43456. _this.inputs.addKeyboard().addMouse();
  43457. return _this;
  43458. }
  43459. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43460. //-- begin properties for backward compatibility for inputs
  43461. /**
  43462. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43463. * Higher values reduce sensitivity.
  43464. */
  43465. get: function () {
  43466. var mouse = this.inputs.attached["mouse"];
  43467. if (mouse)
  43468. return mouse.angularSensibility;
  43469. return 0;
  43470. },
  43471. /**
  43472. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43473. * Higher values reduce sensitivity.
  43474. */
  43475. set: function (value) {
  43476. var mouse = this.inputs.attached["mouse"];
  43477. if (mouse)
  43478. mouse.angularSensibility = value;
  43479. },
  43480. enumerable: true,
  43481. configurable: true
  43482. });
  43483. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43484. get: function () {
  43485. var keyboard = this.inputs.attached["keyboard"];
  43486. if (keyboard)
  43487. return keyboard.keysUp;
  43488. return [];
  43489. },
  43490. set: function (value) {
  43491. var keyboard = this.inputs.attached["keyboard"];
  43492. if (keyboard)
  43493. keyboard.keysUp = value;
  43494. },
  43495. enumerable: true,
  43496. configurable: true
  43497. });
  43498. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43499. get: function () {
  43500. var keyboard = this.inputs.attached["keyboard"];
  43501. if (keyboard)
  43502. return keyboard.keysDown;
  43503. return [];
  43504. },
  43505. set: function (value) {
  43506. var keyboard = this.inputs.attached["keyboard"];
  43507. if (keyboard)
  43508. keyboard.keysDown = value;
  43509. },
  43510. enumerable: true,
  43511. configurable: true
  43512. });
  43513. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43514. get: function () {
  43515. var keyboard = this.inputs.attached["keyboard"];
  43516. if (keyboard)
  43517. return keyboard.keysLeft;
  43518. return [];
  43519. },
  43520. set: function (value) {
  43521. var keyboard = this.inputs.attached["keyboard"];
  43522. if (keyboard)
  43523. keyboard.keysLeft = value;
  43524. },
  43525. enumerable: true,
  43526. configurable: true
  43527. });
  43528. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43529. get: function () {
  43530. var keyboard = this.inputs.attached["keyboard"];
  43531. if (keyboard)
  43532. return keyboard.keysRight;
  43533. return [];
  43534. },
  43535. set: function (value) {
  43536. var keyboard = this.inputs.attached["keyboard"];
  43537. if (keyboard)
  43538. keyboard.keysRight = value;
  43539. },
  43540. enumerable: true,
  43541. configurable: true
  43542. });
  43543. // Controls
  43544. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43545. this.inputs.attachElement(element, noPreventDefault);
  43546. };
  43547. FreeCamera.prototype.detachControl = function (element) {
  43548. this.inputs.detachElement(element);
  43549. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43550. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43551. };
  43552. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43553. get: function () {
  43554. return this._collisionMask;
  43555. },
  43556. set: function (mask) {
  43557. this._collisionMask = !isNaN(mask) ? mask : -1;
  43558. },
  43559. enumerable: true,
  43560. configurable: true
  43561. });
  43562. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43563. var globalPosition;
  43564. if (this.parent) {
  43565. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43566. }
  43567. else {
  43568. globalPosition = this.position;
  43569. }
  43570. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43571. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43572. if (!this._collider) {
  43573. this._collider = new BABYLON.Collider();
  43574. }
  43575. this._collider._radius = this.ellipsoid;
  43576. this._collider.collisionMask = this._collisionMask;
  43577. //no need for clone, as long as gravity is not on.
  43578. var actualDisplacement = displacement;
  43579. //add gravity to the direction to prevent the dual-collision checking
  43580. if (this.applyGravity) {
  43581. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43582. actualDisplacement = displacement.add(this.getScene().gravity);
  43583. }
  43584. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43585. };
  43586. FreeCamera.prototype._checkInputs = function () {
  43587. if (!this._localDirection) {
  43588. this._localDirection = BABYLON.Vector3.Zero();
  43589. this._transformedDirection = BABYLON.Vector3.Zero();
  43590. }
  43591. this.inputs.checkInputs();
  43592. _super.prototype._checkInputs.call(this);
  43593. };
  43594. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43595. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43596. };
  43597. FreeCamera.prototype._updatePosition = function () {
  43598. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43599. this._collideWithWorld(this.cameraDirection);
  43600. }
  43601. else {
  43602. _super.prototype._updatePosition.call(this);
  43603. }
  43604. };
  43605. FreeCamera.prototype.dispose = function () {
  43606. this.inputs.clear();
  43607. _super.prototype.dispose.call(this);
  43608. };
  43609. FreeCamera.prototype.getClassName = function () {
  43610. return "FreeCamera";
  43611. };
  43612. __decorate([
  43613. BABYLON.serializeAsVector3()
  43614. ], FreeCamera.prototype, "ellipsoid", void 0);
  43615. __decorate([
  43616. BABYLON.serializeAsVector3()
  43617. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43618. __decorate([
  43619. BABYLON.serialize()
  43620. ], FreeCamera.prototype, "checkCollisions", void 0);
  43621. __decorate([
  43622. BABYLON.serialize()
  43623. ], FreeCamera.prototype, "applyGravity", void 0);
  43624. return FreeCamera;
  43625. }(BABYLON.TargetCamera));
  43626. BABYLON.FreeCamera = FreeCamera;
  43627. })(BABYLON || (BABYLON = {}));
  43628. //# sourceMappingURL=babylon.freeCamera.js.map
  43629. var BABYLON;
  43630. (function (BABYLON) {
  43631. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43632. function ArcRotateCameraKeyboardMoveInput() {
  43633. this._keys = new Array();
  43634. this.keysUp = [38];
  43635. this.keysDown = [40];
  43636. this.keysLeft = [37];
  43637. this.keysRight = [39];
  43638. this.keysReset = [220];
  43639. this.panningSensibility = 50.0;
  43640. this.zoomingSensibility = 25.0;
  43641. this.useAltToZoom = true;
  43642. }
  43643. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43644. var _this = this;
  43645. if (this._onCanvasBlurObserver) {
  43646. return;
  43647. }
  43648. this._scene = this.camera.getScene();
  43649. this._engine = this._scene.getEngine();
  43650. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43651. _this._keys = [];
  43652. });
  43653. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43654. var evt = info.event;
  43655. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43656. _this._ctrlPressed = evt.ctrlKey;
  43657. _this._altPressed = evt.altKey;
  43658. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43659. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43660. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43661. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43662. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43663. var index = _this._keys.indexOf(evt.keyCode);
  43664. if (index === -1) {
  43665. _this._keys.push(evt.keyCode);
  43666. }
  43667. if (evt.preventDefault) {
  43668. if (!noPreventDefault) {
  43669. evt.preventDefault();
  43670. }
  43671. }
  43672. }
  43673. }
  43674. else {
  43675. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43676. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43677. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43678. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43679. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43680. var index = _this._keys.indexOf(evt.keyCode);
  43681. if (index >= 0) {
  43682. _this._keys.splice(index, 1);
  43683. }
  43684. if (evt.preventDefault) {
  43685. if (!noPreventDefault) {
  43686. evt.preventDefault();
  43687. }
  43688. }
  43689. }
  43690. }
  43691. });
  43692. };
  43693. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43694. if (this._scene) {
  43695. if (this._onKeyboardObserver) {
  43696. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43697. }
  43698. if (this._onCanvasBlurObserver) {
  43699. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43700. }
  43701. this._onKeyboardObserver = null;
  43702. this._onCanvasBlurObserver = null;
  43703. }
  43704. this._keys = [];
  43705. };
  43706. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43707. if (this._onKeyboardObserver) {
  43708. var camera = this.camera;
  43709. for (var index = 0; index < this._keys.length; index++) {
  43710. var keyCode = this._keys[index];
  43711. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43712. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43713. camera.inertialPanningX -= 1 / this.panningSensibility;
  43714. }
  43715. else {
  43716. camera.inertialAlphaOffset -= 0.01;
  43717. }
  43718. }
  43719. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43720. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43721. camera.inertialPanningY += 1 / this.panningSensibility;
  43722. }
  43723. else if (this._altPressed && this.useAltToZoom) {
  43724. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43725. }
  43726. else {
  43727. camera.inertialBetaOffset -= 0.01;
  43728. }
  43729. }
  43730. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43731. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43732. camera.inertialPanningX += 1 / this.panningSensibility;
  43733. }
  43734. else {
  43735. camera.inertialAlphaOffset += 0.01;
  43736. }
  43737. }
  43738. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43739. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43740. camera.inertialPanningY -= 1 / this.panningSensibility;
  43741. }
  43742. else if (this._altPressed && this.useAltToZoom) {
  43743. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43744. }
  43745. else {
  43746. camera.inertialBetaOffset += 0.01;
  43747. }
  43748. }
  43749. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43750. camera.restoreState();
  43751. }
  43752. }
  43753. }
  43754. };
  43755. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43756. return "ArcRotateCameraKeyboardMoveInput";
  43757. };
  43758. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43759. return "keyboard";
  43760. };
  43761. __decorate([
  43762. BABYLON.serialize()
  43763. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43764. __decorate([
  43765. BABYLON.serialize()
  43766. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43767. __decorate([
  43768. BABYLON.serialize()
  43769. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43770. __decorate([
  43771. BABYLON.serialize()
  43772. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43773. __decorate([
  43774. BABYLON.serialize()
  43775. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43776. __decorate([
  43777. BABYLON.serialize()
  43778. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43779. __decorate([
  43780. BABYLON.serialize()
  43781. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43782. __decorate([
  43783. BABYLON.serialize()
  43784. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43785. return ArcRotateCameraKeyboardMoveInput;
  43786. }());
  43787. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43788. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43789. })(BABYLON || (BABYLON = {}));
  43790. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43791. var BABYLON;
  43792. (function (BABYLON) {
  43793. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43794. function ArcRotateCameraMouseWheelInput() {
  43795. this.wheelPrecision = 3.0;
  43796. /**
  43797. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43798. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43799. */
  43800. this.wheelDeltaPercentage = 0;
  43801. }
  43802. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43803. var _this = this;
  43804. this._wheel = function (p, s) {
  43805. //sanity check - this should be a PointerWheel event.
  43806. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43807. return;
  43808. var event = p.event;
  43809. var delta = 0;
  43810. if (event.wheelDelta) {
  43811. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43812. }
  43813. else if (event.detail) {
  43814. delta = -event.detail / _this.wheelPrecision;
  43815. }
  43816. if (delta)
  43817. _this.camera.inertialRadiusOffset += delta;
  43818. if (event.preventDefault) {
  43819. if (!noPreventDefault) {
  43820. event.preventDefault();
  43821. }
  43822. }
  43823. };
  43824. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43825. };
  43826. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43827. if (this._observer && element) {
  43828. this.camera.getScene().onPointerObservable.remove(this._observer);
  43829. this._observer = null;
  43830. this._wheel = null;
  43831. }
  43832. };
  43833. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43834. return "ArcRotateCameraMouseWheelInput";
  43835. };
  43836. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43837. return "mousewheel";
  43838. };
  43839. __decorate([
  43840. BABYLON.serialize()
  43841. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43842. __decorate([
  43843. BABYLON.serialize()
  43844. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43845. return ArcRotateCameraMouseWheelInput;
  43846. }());
  43847. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43848. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43849. })(BABYLON || (BABYLON = {}));
  43850. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43851. var BABYLON;
  43852. (function (BABYLON) {
  43853. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43854. function ArcRotateCameraPointersInput() {
  43855. this.buttons = [0, 1, 2];
  43856. this.angularSensibilityX = 1000.0;
  43857. this.angularSensibilityY = 1000.0;
  43858. this.pinchPrecision = 12.0;
  43859. /**
  43860. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43861. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43862. */
  43863. this.pinchDeltaPercentage = 0;
  43864. this.panningSensibility = 1000.0;
  43865. this.multiTouchPanning = true;
  43866. this.multiTouchPanAndZoom = true;
  43867. this._isPanClick = false;
  43868. this.pinchInwards = true;
  43869. }
  43870. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43871. var _this = this;
  43872. var engine = this.camera.getEngine();
  43873. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43874. var pointA = null;
  43875. var pointB = null;
  43876. var previousPinchSquaredDistance = 0;
  43877. var initialDistance = 0;
  43878. var twoFingerActivityCount = 0;
  43879. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43880. this._pointerInput = function (p, s) {
  43881. var evt = p.event;
  43882. var isTouch = p.event.pointerType === "touch";
  43883. if (engine.isInVRExclusivePointerMode) {
  43884. return;
  43885. }
  43886. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43887. return;
  43888. }
  43889. var srcElement = (evt.srcElement || evt.target);
  43890. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43891. try {
  43892. srcElement.setPointerCapture(evt.pointerId);
  43893. }
  43894. catch (e) {
  43895. //Nothing to do with the error. Execution will continue.
  43896. }
  43897. // Manage panning with pan button click
  43898. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43899. // manage pointers
  43900. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43901. if (pointA === null) {
  43902. pointA = cacheSoloPointer;
  43903. }
  43904. else if (pointB === null) {
  43905. pointB = cacheSoloPointer;
  43906. }
  43907. if (!noPreventDefault) {
  43908. evt.preventDefault();
  43909. element.focus();
  43910. }
  43911. }
  43912. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43913. _this.camera.restoreState();
  43914. }
  43915. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43916. try {
  43917. srcElement.releasePointerCapture(evt.pointerId);
  43918. }
  43919. catch (e) {
  43920. //Nothing to do with the error.
  43921. }
  43922. cacheSoloPointer = null;
  43923. previousPinchSquaredDistance = 0;
  43924. previousMultiTouchPanPosition.isPaning = false;
  43925. previousMultiTouchPanPosition.isPinching = false;
  43926. twoFingerActivityCount = 0;
  43927. initialDistance = 0;
  43928. if (!isTouch) {
  43929. pointB = null; // Mouse and pen are mono pointer
  43930. }
  43931. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43932. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43933. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43934. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43935. if (engine.badOS) {
  43936. pointA = pointB = null;
  43937. }
  43938. else {
  43939. //only remove the impacted pointer in case of multitouch allowing on most
  43940. //platforms switching from rotate to zoom and pan seamlessly.
  43941. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43942. pointA = pointB;
  43943. pointB = null;
  43944. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43945. }
  43946. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43947. pointB = null;
  43948. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43949. }
  43950. else {
  43951. pointA = pointB = null;
  43952. }
  43953. }
  43954. if (!noPreventDefault) {
  43955. evt.preventDefault();
  43956. }
  43957. }
  43958. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43959. if (!noPreventDefault) {
  43960. evt.preventDefault();
  43961. }
  43962. // One button down
  43963. if (pointA && pointB === null && cacheSoloPointer) {
  43964. if (_this.panningSensibility !== 0 &&
  43965. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43966. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43967. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43968. }
  43969. else {
  43970. var offsetX = evt.clientX - cacheSoloPointer.x;
  43971. var offsetY = evt.clientY - cacheSoloPointer.y;
  43972. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43973. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43974. }
  43975. cacheSoloPointer.x = evt.clientX;
  43976. cacheSoloPointer.y = evt.clientY;
  43977. }
  43978. else if (pointA && pointB) {
  43979. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43980. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43981. ed.x = evt.clientX;
  43982. ed.y = evt.clientY;
  43983. var direction = _this.pinchInwards ? 1 : -1;
  43984. var distX = pointA.x - pointB.x;
  43985. var distY = pointA.y - pointB.y;
  43986. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43987. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43988. if (previousPinchSquaredDistance === 0) {
  43989. initialDistance = pinchDistance;
  43990. previousPinchSquaredDistance = pinchSquaredDistance;
  43991. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43992. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43993. return;
  43994. }
  43995. if (_this.multiTouchPanAndZoom) {
  43996. if (_this.pinchDeltaPercentage) {
  43997. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43998. }
  43999. else {
  44000. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44001. (_this.pinchPrecision *
  44002. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44003. direction);
  44004. }
  44005. if (_this.panningSensibility !== 0) {
  44006. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44007. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44008. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44009. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44010. previousMultiTouchPanPosition.x = pointersCenterX;
  44011. previousMultiTouchPanPosition.y = pointersCenterY;
  44012. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44013. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44014. }
  44015. }
  44016. else {
  44017. twoFingerActivityCount++;
  44018. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44019. if (_this.pinchDeltaPercentage) {
  44020. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44021. }
  44022. else {
  44023. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44024. (_this.pinchPrecision *
  44025. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44026. direction);
  44027. }
  44028. previousMultiTouchPanPosition.isPaning = false;
  44029. previousMultiTouchPanPosition.isPinching = true;
  44030. }
  44031. else {
  44032. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44033. if (!previousMultiTouchPanPosition.isPaning) {
  44034. previousMultiTouchPanPosition.isPaning = true;
  44035. previousMultiTouchPanPosition.isPinching = false;
  44036. previousMultiTouchPanPosition.x = ed.x;
  44037. previousMultiTouchPanPosition.y = ed.y;
  44038. return;
  44039. }
  44040. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44041. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44042. }
  44043. }
  44044. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44045. previousMultiTouchPanPosition.x = ed.x;
  44046. previousMultiTouchPanPosition.y = ed.y;
  44047. }
  44048. }
  44049. previousPinchSquaredDistance = pinchSquaredDistance;
  44050. }
  44051. }
  44052. };
  44053. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44054. this._onContextMenu = function (evt) {
  44055. evt.preventDefault();
  44056. };
  44057. if (!this.camera._useCtrlForPanning) {
  44058. element.addEventListener("contextmenu", this._onContextMenu, false);
  44059. }
  44060. this._onLostFocus = function () {
  44061. //this._keys = [];
  44062. pointA = pointB = null;
  44063. previousPinchSquaredDistance = 0;
  44064. previousMultiTouchPanPosition.isPaning = false;
  44065. previousMultiTouchPanPosition.isPinching = false;
  44066. twoFingerActivityCount = 0;
  44067. cacheSoloPointer = null;
  44068. initialDistance = 0;
  44069. };
  44070. this._onMouseMove = function (evt) {
  44071. if (!engine.isPointerLock) {
  44072. return;
  44073. }
  44074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44076. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44077. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44078. if (!noPreventDefault) {
  44079. evt.preventDefault();
  44080. }
  44081. };
  44082. this._onGestureStart = function (e) {
  44083. if (window.MSGesture === undefined) {
  44084. return;
  44085. }
  44086. if (!_this._MSGestureHandler) {
  44087. _this._MSGestureHandler = new MSGesture();
  44088. _this._MSGestureHandler.target = element;
  44089. }
  44090. _this._MSGestureHandler.addPointer(e.pointerId);
  44091. };
  44092. this._onGesture = function (e) {
  44093. _this.camera.radius *= e.scale;
  44094. if (e.preventDefault) {
  44095. if (!noPreventDefault) {
  44096. e.stopPropagation();
  44097. e.preventDefault();
  44098. }
  44099. }
  44100. };
  44101. element.addEventListener("mousemove", this._onMouseMove, false);
  44102. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44103. element.addEventListener("MSGestureChange", this._onGesture, false);
  44104. BABYLON.Tools.RegisterTopRootEvents([
  44105. { name: "blur", handler: this._onLostFocus }
  44106. ]);
  44107. };
  44108. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44109. if (this._onLostFocus) {
  44110. BABYLON.Tools.UnregisterTopRootEvents([
  44111. { name: "blur", handler: this._onLostFocus }
  44112. ]);
  44113. }
  44114. if (element && this._observer) {
  44115. this.camera.getScene().onPointerObservable.remove(this._observer);
  44116. this._observer = null;
  44117. if (this._onContextMenu) {
  44118. element.removeEventListener("contextmenu", this._onContextMenu);
  44119. }
  44120. if (this._onMouseMove) {
  44121. element.removeEventListener("mousemove", this._onMouseMove);
  44122. }
  44123. if (this._onGestureStart) {
  44124. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44125. }
  44126. if (this._onGesture) {
  44127. element.removeEventListener("MSGestureChange", this._onGesture);
  44128. }
  44129. this._isPanClick = false;
  44130. this.pinchInwards = true;
  44131. this._onMouseMove = null;
  44132. this._onGestureStart = null;
  44133. this._onGesture = null;
  44134. this._MSGestureHandler = null;
  44135. this._onLostFocus = null;
  44136. this._onContextMenu = null;
  44137. }
  44138. };
  44139. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44140. return "ArcRotateCameraPointersInput";
  44141. };
  44142. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44143. return "pointers";
  44144. };
  44145. __decorate([
  44146. BABYLON.serialize()
  44147. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44148. __decorate([
  44149. BABYLON.serialize()
  44150. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44151. __decorate([
  44152. BABYLON.serialize()
  44153. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44154. __decorate([
  44155. BABYLON.serialize()
  44156. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44157. __decorate([
  44158. BABYLON.serialize()
  44159. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44160. __decorate([
  44161. BABYLON.serialize()
  44162. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44163. __decorate([
  44164. BABYLON.serialize()
  44165. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44166. __decorate([
  44167. BABYLON.serialize()
  44168. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44169. return ArcRotateCameraPointersInput;
  44170. }());
  44171. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44172. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44173. })(BABYLON || (BABYLON = {}));
  44174. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44175. var BABYLON;
  44176. (function (BABYLON) {
  44177. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44178. __extends(ArcRotateCameraInputsManager, _super);
  44179. function ArcRotateCameraInputsManager(camera) {
  44180. return _super.call(this, camera) || this;
  44181. }
  44182. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44183. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44184. return this;
  44185. };
  44186. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44187. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44188. return this;
  44189. };
  44190. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44191. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44192. return this;
  44193. };
  44194. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44195. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44196. return this;
  44197. };
  44198. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44199. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44200. return this;
  44201. };
  44202. return ArcRotateCameraInputsManager;
  44203. }(BABYLON.CameraInputsManager));
  44204. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44205. })(BABYLON || (BABYLON = {}));
  44206. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44207. var BABYLON;
  44208. (function (BABYLON) {
  44209. var ArcRotateCamera = /** @class */ (function (_super) {
  44210. __extends(ArcRotateCamera, _super);
  44211. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44212. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44213. _this.inertialAlphaOffset = 0;
  44214. _this.inertialBetaOffset = 0;
  44215. _this.inertialRadiusOffset = 0;
  44216. _this.lowerAlphaLimit = null;
  44217. _this.upperAlphaLimit = null;
  44218. _this.lowerBetaLimit = 0.01;
  44219. _this.upperBetaLimit = Math.PI;
  44220. _this.lowerRadiusLimit = null;
  44221. _this.upperRadiusLimit = null;
  44222. _this.inertialPanningX = 0;
  44223. _this.inertialPanningY = 0;
  44224. _this.pinchToPanMaxDistance = 20;
  44225. _this.panningDistanceLimit = null;
  44226. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44227. _this.panningInertia = 0.9;
  44228. //-- end properties for backward compatibility for inputs
  44229. _this.zoomOnFactor = 1;
  44230. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44231. _this.allowUpsideDown = true;
  44232. _this._viewMatrix = new BABYLON.Matrix();
  44233. // Panning
  44234. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44235. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44236. _this.checkCollisions = false;
  44237. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44238. _this._previousPosition = BABYLON.Vector3.Zero();
  44239. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44240. _this._newPosition = BABYLON.Vector3.Zero();
  44241. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44242. if (collidedMesh === void 0) { collidedMesh = null; }
  44243. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44244. newPosition.multiplyInPlace(_this._collider._radius);
  44245. }
  44246. if (!collidedMesh) {
  44247. _this._previousPosition.copyFrom(_this.position);
  44248. }
  44249. else {
  44250. _this.setPosition(newPosition);
  44251. if (_this.onCollide) {
  44252. _this.onCollide(collidedMesh);
  44253. }
  44254. }
  44255. // Recompute because of constraints
  44256. var cosa = Math.cos(_this.alpha);
  44257. var sina = Math.sin(_this.alpha);
  44258. var cosb = Math.cos(_this.beta);
  44259. var sinb = Math.sin(_this.beta);
  44260. if (sinb === 0) {
  44261. sinb = 0.0001;
  44262. }
  44263. var target = _this._getTargetPosition();
  44264. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44265. _this.position.copyFrom(_this._newPosition);
  44266. var up = _this.upVector;
  44267. if (_this.allowUpsideDown && _this.beta < 0) {
  44268. up = up.clone();
  44269. up = up.negate();
  44270. }
  44271. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44272. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44273. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44274. _this._collisionTriggered = false;
  44275. };
  44276. _this._target = BABYLON.Vector3.Zero();
  44277. if (target) {
  44278. _this.setTarget(target);
  44279. }
  44280. _this.alpha = alpha;
  44281. _this.beta = beta;
  44282. _this.radius = radius;
  44283. _this.getViewMatrix();
  44284. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44285. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44286. return _this;
  44287. }
  44288. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44289. get: function () {
  44290. return this._target;
  44291. },
  44292. set: function (value) {
  44293. this.setTarget(value);
  44294. },
  44295. enumerable: true,
  44296. configurable: true
  44297. });
  44298. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44299. //-- begin properties for backward compatibility for inputs
  44300. get: function () {
  44301. var pointers = this.inputs.attached["pointers"];
  44302. if (pointers)
  44303. return pointers.angularSensibilityX;
  44304. return 0;
  44305. },
  44306. set: function (value) {
  44307. var pointers = this.inputs.attached["pointers"];
  44308. if (pointers) {
  44309. pointers.angularSensibilityX = value;
  44310. }
  44311. },
  44312. enumerable: true,
  44313. configurable: true
  44314. });
  44315. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44316. get: function () {
  44317. var pointers = this.inputs.attached["pointers"];
  44318. if (pointers)
  44319. return pointers.angularSensibilityY;
  44320. return 0;
  44321. },
  44322. set: function (value) {
  44323. var pointers = this.inputs.attached["pointers"];
  44324. if (pointers) {
  44325. pointers.angularSensibilityY = value;
  44326. }
  44327. },
  44328. enumerable: true,
  44329. configurable: true
  44330. });
  44331. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44332. get: function () {
  44333. var pointers = this.inputs.attached["pointers"];
  44334. if (pointers)
  44335. return pointers.pinchPrecision;
  44336. return 0;
  44337. },
  44338. set: function (value) {
  44339. var pointers = this.inputs.attached["pointers"];
  44340. if (pointers) {
  44341. pointers.pinchPrecision = value;
  44342. }
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44348. get: function () {
  44349. var pointers = this.inputs.attached["pointers"];
  44350. if (pointers)
  44351. return pointers.pinchDeltaPercentage;
  44352. return 0;
  44353. },
  44354. set: function (value) {
  44355. var pointers = this.inputs.attached["pointers"];
  44356. if (pointers) {
  44357. pointers.pinchDeltaPercentage = value;
  44358. }
  44359. },
  44360. enumerable: true,
  44361. configurable: true
  44362. });
  44363. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44364. get: function () {
  44365. var pointers = this.inputs.attached["pointers"];
  44366. if (pointers)
  44367. return pointers.panningSensibility;
  44368. return 0;
  44369. },
  44370. set: function (value) {
  44371. var pointers = this.inputs.attached["pointers"];
  44372. if (pointers) {
  44373. pointers.panningSensibility = value;
  44374. }
  44375. },
  44376. enumerable: true,
  44377. configurable: true
  44378. });
  44379. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44380. get: function () {
  44381. var keyboard = this.inputs.attached["keyboard"];
  44382. if (keyboard)
  44383. return keyboard.keysUp;
  44384. return [];
  44385. },
  44386. set: function (value) {
  44387. var keyboard = this.inputs.attached["keyboard"];
  44388. if (keyboard)
  44389. keyboard.keysUp = value;
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44395. get: function () {
  44396. var keyboard = this.inputs.attached["keyboard"];
  44397. if (keyboard)
  44398. return keyboard.keysDown;
  44399. return [];
  44400. },
  44401. set: function (value) {
  44402. var keyboard = this.inputs.attached["keyboard"];
  44403. if (keyboard)
  44404. keyboard.keysDown = value;
  44405. },
  44406. enumerable: true,
  44407. configurable: true
  44408. });
  44409. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44410. get: function () {
  44411. var keyboard = this.inputs.attached["keyboard"];
  44412. if (keyboard)
  44413. return keyboard.keysLeft;
  44414. return [];
  44415. },
  44416. set: function (value) {
  44417. var keyboard = this.inputs.attached["keyboard"];
  44418. if (keyboard)
  44419. keyboard.keysLeft = value;
  44420. },
  44421. enumerable: true,
  44422. configurable: true
  44423. });
  44424. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44425. get: function () {
  44426. var keyboard = this.inputs.attached["keyboard"];
  44427. if (keyboard)
  44428. return keyboard.keysRight;
  44429. return [];
  44430. },
  44431. set: function (value) {
  44432. var keyboard = this.inputs.attached["keyboard"];
  44433. if (keyboard)
  44434. keyboard.keysRight = value;
  44435. },
  44436. enumerable: true,
  44437. configurable: true
  44438. });
  44439. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44440. get: function () {
  44441. var mousewheel = this.inputs.attached["mousewheel"];
  44442. if (mousewheel)
  44443. return mousewheel.wheelPrecision;
  44444. return 0;
  44445. },
  44446. set: function (value) {
  44447. var mousewheel = this.inputs.attached["mousewheel"];
  44448. if (mousewheel)
  44449. mousewheel.wheelPrecision = value;
  44450. },
  44451. enumerable: true,
  44452. configurable: true
  44453. });
  44454. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44455. get: function () {
  44456. var mousewheel = this.inputs.attached["mousewheel"];
  44457. if (mousewheel)
  44458. return mousewheel.wheelDeltaPercentage;
  44459. return 0;
  44460. },
  44461. set: function (value) {
  44462. var mousewheel = this.inputs.attached["mousewheel"];
  44463. if (mousewheel)
  44464. mousewheel.wheelDeltaPercentage = value;
  44465. },
  44466. enumerable: true,
  44467. configurable: true
  44468. });
  44469. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44470. get: function () {
  44471. return this._bouncingBehavior;
  44472. },
  44473. enumerable: true,
  44474. configurable: true
  44475. });
  44476. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44477. get: function () {
  44478. return this._bouncingBehavior != null;
  44479. },
  44480. set: function (value) {
  44481. if (value === this.useBouncingBehavior) {
  44482. return;
  44483. }
  44484. if (value) {
  44485. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44486. this.addBehavior(this._bouncingBehavior);
  44487. }
  44488. else if (this._bouncingBehavior) {
  44489. this.removeBehavior(this._bouncingBehavior);
  44490. this._bouncingBehavior = null;
  44491. }
  44492. },
  44493. enumerable: true,
  44494. configurable: true
  44495. });
  44496. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44497. get: function () {
  44498. return this._framingBehavior;
  44499. },
  44500. enumerable: true,
  44501. configurable: true
  44502. });
  44503. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44504. get: function () {
  44505. return this._framingBehavior != null;
  44506. },
  44507. set: function (value) {
  44508. if (value === this.useFramingBehavior) {
  44509. return;
  44510. }
  44511. if (value) {
  44512. this._framingBehavior = new BABYLON.FramingBehavior();
  44513. this.addBehavior(this._framingBehavior);
  44514. }
  44515. else if (this._framingBehavior) {
  44516. this.removeBehavior(this._framingBehavior);
  44517. this._framingBehavior = null;
  44518. }
  44519. },
  44520. enumerable: true,
  44521. configurable: true
  44522. });
  44523. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44524. get: function () {
  44525. return this._autoRotationBehavior;
  44526. },
  44527. enumerable: true,
  44528. configurable: true
  44529. });
  44530. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44531. get: function () {
  44532. return this._autoRotationBehavior != null;
  44533. },
  44534. set: function (value) {
  44535. if (value === this.useAutoRotationBehavior) {
  44536. return;
  44537. }
  44538. if (value) {
  44539. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44540. this.addBehavior(this._autoRotationBehavior);
  44541. }
  44542. else if (this._autoRotationBehavior) {
  44543. this.removeBehavior(this._autoRotationBehavior);
  44544. this._autoRotationBehavior = null;
  44545. }
  44546. },
  44547. enumerable: true,
  44548. configurable: true
  44549. });
  44550. // Cache
  44551. ArcRotateCamera.prototype._initCache = function () {
  44552. _super.prototype._initCache.call(this);
  44553. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44554. this._cache.alpha = undefined;
  44555. this._cache.beta = undefined;
  44556. this._cache.radius = undefined;
  44557. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44558. };
  44559. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44560. if (!ignoreParentClass) {
  44561. _super.prototype._updateCache.call(this);
  44562. }
  44563. this._cache._target.copyFrom(this._getTargetPosition());
  44564. this._cache.alpha = this.alpha;
  44565. this._cache.beta = this.beta;
  44566. this._cache.radius = this.radius;
  44567. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44568. };
  44569. ArcRotateCamera.prototype._getTargetPosition = function () {
  44570. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44571. var pos = this._targetHost.getAbsolutePosition();
  44572. if (this._targetBoundingCenter) {
  44573. pos.addToRef(this._targetBoundingCenter, this._target);
  44574. }
  44575. else {
  44576. this._target.copyFrom(pos);
  44577. }
  44578. }
  44579. var lockedTargetPosition = this._getLockedTargetPosition();
  44580. if (lockedTargetPosition) {
  44581. return lockedTargetPosition;
  44582. }
  44583. return this._target;
  44584. };
  44585. ArcRotateCamera.prototype.storeState = function () {
  44586. this._storedAlpha = this.alpha;
  44587. this._storedBeta = this.beta;
  44588. this._storedRadius = this.radius;
  44589. this._storedTarget = this._getTargetPosition().clone();
  44590. return _super.prototype.storeState.call(this);
  44591. };
  44592. /**
  44593. * Restored camera state. You must call storeState() first
  44594. */
  44595. ArcRotateCamera.prototype._restoreStateValues = function () {
  44596. if (!_super.prototype._restoreStateValues.call(this)) {
  44597. return false;
  44598. }
  44599. this.alpha = this._storedAlpha;
  44600. this.beta = this._storedBeta;
  44601. this.radius = this._storedRadius;
  44602. this.setTarget(this._storedTarget.clone());
  44603. this.inertialAlphaOffset = 0;
  44604. this.inertialBetaOffset = 0;
  44605. this.inertialRadiusOffset = 0;
  44606. this.inertialPanningX = 0;
  44607. this.inertialPanningY = 0;
  44608. return true;
  44609. };
  44610. // Synchronized
  44611. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44612. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44613. return false;
  44614. return this._cache._target.equals(this._getTargetPosition())
  44615. && this._cache.alpha === this.alpha
  44616. && this._cache.beta === this.beta
  44617. && this._cache.radius === this.radius
  44618. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44619. };
  44620. // Methods
  44621. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44622. var _this = this;
  44623. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44624. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44625. this._useCtrlForPanning = useCtrlForPanning;
  44626. this._panningMouseButton = panningMouseButton;
  44627. this.inputs.attachElement(element, noPreventDefault);
  44628. this._reset = function () {
  44629. _this.inertialAlphaOffset = 0;
  44630. _this.inertialBetaOffset = 0;
  44631. _this.inertialRadiusOffset = 0;
  44632. _this.inertialPanningX = 0;
  44633. _this.inertialPanningY = 0;
  44634. };
  44635. };
  44636. ArcRotateCamera.prototype.detachControl = function (element) {
  44637. this.inputs.detachElement(element);
  44638. if (this._reset) {
  44639. this._reset();
  44640. }
  44641. };
  44642. ArcRotateCamera.prototype._checkInputs = function () {
  44643. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44644. if (this._collisionTriggered) {
  44645. return;
  44646. }
  44647. this.inputs.checkInputs();
  44648. // Inertia
  44649. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44650. if (this.getScene().useRightHandedSystem) {
  44651. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44652. }
  44653. else {
  44654. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44655. }
  44656. this.beta += this.inertialBetaOffset;
  44657. this.radius -= this.inertialRadiusOffset;
  44658. this.inertialAlphaOffset *= this.inertia;
  44659. this.inertialBetaOffset *= this.inertia;
  44660. this.inertialRadiusOffset *= this.inertia;
  44661. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44662. this.inertialAlphaOffset = 0;
  44663. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44664. this.inertialBetaOffset = 0;
  44665. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44666. this.inertialRadiusOffset = 0;
  44667. }
  44668. // Panning inertia
  44669. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44670. if (!this._localDirection) {
  44671. this._localDirection = BABYLON.Vector3.Zero();
  44672. this._transformedDirection = BABYLON.Vector3.Zero();
  44673. }
  44674. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44675. this._localDirection.multiplyInPlace(this.panningAxis);
  44676. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44677. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44678. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44679. if (!this.panningAxis.y) {
  44680. this._transformedDirection.y = 0;
  44681. }
  44682. if (!this._targetHost) {
  44683. if (this.panningDistanceLimit) {
  44684. this._transformedDirection.addInPlace(this._target);
  44685. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44686. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44687. this._target.copyFrom(this._transformedDirection);
  44688. }
  44689. }
  44690. else {
  44691. this._target.addInPlace(this._transformedDirection);
  44692. }
  44693. }
  44694. this.inertialPanningX *= this.panningInertia;
  44695. this.inertialPanningY *= this.panningInertia;
  44696. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44697. this.inertialPanningX = 0;
  44698. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44699. this.inertialPanningY = 0;
  44700. }
  44701. // Limits
  44702. this._checkLimits();
  44703. _super.prototype._checkInputs.call(this);
  44704. };
  44705. ArcRotateCamera.prototype._checkLimits = function () {
  44706. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44707. if (this.allowUpsideDown && this.beta > Math.PI) {
  44708. this.beta = this.beta - (2 * Math.PI);
  44709. }
  44710. }
  44711. else {
  44712. if (this.beta < this.lowerBetaLimit) {
  44713. this.beta = this.lowerBetaLimit;
  44714. }
  44715. }
  44716. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44717. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44718. this.beta = this.beta + (2 * Math.PI);
  44719. }
  44720. }
  44721. else {
  44722. if (this.beta > this.upperBetaLimit) {
  44723. this.beta = this.upperBetaLimit;
  44724. }
  44725. }
  44726. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44727. this.alpha = this.lowerAlphaLimit;
  44728. }
  44729. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44730. this.alpha = this.upperAlphaLimit;
  44731. }
  44732. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44733. this.radius = this.lowerRadiusLimit;
  44734. }
  44735. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44736. this.radius = this.upperRadiusLimit;
  44737. }
  44738. };
  44739. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44740. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44741. this.radius = radiusv3.length();
  44742. if (this.radius === 0) {
  44743. this.radius = 0.0001; // Just to avoid division by zero
  44744. }
  44745. // Alpha
  44746. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44747. if (radiusv3.z < 0) {
  44748. this.alpha = 2 * Math.PI - this.alpha;
  44749. }
  44750. // Beta
  44751. this.beta = Math.acos(radiusv3.y / this.radius);
  44752. this._checkLimits();
  44753. };
  44754. ArcRotateCamera.prototype.setPosition = function (position) {
  44755. if (this.position.equals(position)) {
  44756. return;
  44757. }
  44758. this.position.copyFrom(position);
  44759. this.rebuildAnglesAndRadius();
  44760. };
  44761. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44762. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44763. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44764. if (target.getBoundingInfo) {
  44765. if (toBoundingCenter) {
  44766. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44767. }
  44768. else {
  44769. this._targetBoundingCenter = null;
  44770. }
  44771. this._targetHost = target;
  44772. this._target = this._getTargetPosition();
  44773. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44774. }
  44775. else {
  44776. var newTarget = target;
  44777. var currentTarget = this._getTargetPosition();
  44778. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44779. return;
  44780. }
  44781. this._targetHost = null;
  44782. this._target = newTarget;
  44783. this._targetBoundingCenter = null;
  44784. this.onMeshTargetChangedObservable.notifyObservers(null);
  44785. }
  44786. this.rebuildAnglesAndRadius();
  44787. };
  44788. ArcRotateCamera.prototype._getViewMatrix = function () {
  44789. // Compute
  44790. var cosa = Math.cos(this.alpha);
  44791. var sina = Math.sin(this.alpha);
  44792. var cosb = Math.cos(this.beta);
  44793. var sinb = Math.sin(this.beta);
  44794. if (sinb === 0) {
  44795. sinb = 0.0001;
  44796. }
  44797. var target = this._getTargetPosition();
  44798. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44799. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44800. if (!this._collider) {
  44801. this._collider = new BABYLON.Collider();
  44802. }
  44803. this._collider._radius = this.collisionRadius;
  44804. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44805. this._collisionTriggered = true;
  44806. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44807. }
  44808. else {
  44809. this.position.copyFrom(this._newPosition);
  44810. var up = this.upVector;
  44811. if (this.allowUpsideDown && sinb < 0) {
  44812. up = up.clone();
  44813. up = up.negate();
  44814. }
  44815. if (this.getScene().useRightHandedSystem) {
  44816. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44817. }
  44818. else {
  44819. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44820. }
  44821. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44822. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44823. }
  44824. this._currentTarget = target;
  44825. return this._viewMatrix;
  44826. };
  44827. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44828. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44829. meshes = meshes || this.getScene().meshes;
  44830. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44831. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44832. this.radius = distance * this.zoomOnFactor;
  44833. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44834. };
  44835. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44836. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44837. var meshesOrMinMaxVector;
  44838. var distance;
  44839. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44840. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44841. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44842. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44843. }
  44844. else {
  44845. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44846. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44847. distance = minMaxVectorAndDistance.distance;
  44848. }
  44849. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44850. if (!doNotUpdateMaxZ) {
  44851. this.maxZ = distance * 2;
  44852. }
  44853. };
  44854. /**
  44855. * @override
  44856. * Override Camera.createRigCamera
  44857. */
  44858. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44859. var alphaShift = 0;
  44860. switch (this.cameraRigMode) {
  44861. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44862. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44863. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44864. case BABYLON.Camera.RIG_MODE_VR:
  44865. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44866. break;
  44867. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44868. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44869. break;
  44870. }
  44871. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44872. rigCam._cameraRigParams = {};
  44873. return rigCam;
  44874. };
  44875. /**
  44876. * @override
  44877. * Override Camera._updateRigCameras
  44878. */
  44879. ArcRotateCamera.prototype._updateRigCameras = function () {
  44880. var camLeft = this._rigCameras[0];
  44881. var camRight = this._rigCameras[1];
  44882. camLeft.beta = camRight.beta = this.beta;
  44883. camLeft.radius = camRight.radius = this.radius;
  44884. switch (this.cameraRigMode) {
  44885. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44887. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44888. case BABYLON.Camera.RIG_MODE_VR:
  44889. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44890. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44891. break;
  44892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44893. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44894. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44895. break;
  44896. }
  44897. _super.prototype._updateRigCameras.call(this);
  44898. };
  44899. ArcRotateCamera.prototype.dispose = function () {
  44900. this.inputs.clear();
  44901. _super.prototype.dispose.call(this);
  44902. };
  44903. ArcRotateCamera.prototype.getClassName = function () {
  44904. return "ArcRotateCamera";
  44905. };
  44906. __decorate([
  44907. BABYLON.serialize()
  44908. ], ArcRotateCamera.prototype, "alpha", void 0);
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], ArcRotateCamera.prototype, "beta", void 0);
  44912. __decorate([
  44913. BABYLON.serialize()
  44914. ], ArcRotateCamera.prototype, "radius", void 0);
  44915. __decorate([
  44916. BABYLON.serializeAsVector3("target")
  44917. ], ArcRotateCamera.prototype, "_target", void 0);
  44918. __decorate([
  44919. BABYLON.serialize()
  44920. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44921. __decorate([
  44922. BABYLON.serialize()
  44923. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44924. __decorate([
  44925. BABYLON.serialize()
  44926. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44927. __decorate([
  44928. BABYLON.serialize()
  44929. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44930. __decorate([
  44931. BABYLON.serialize()
  44932. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44933. __decorate([
  44934. BABYLON.serialize()
  44935. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44936. __decorate([
  44937. BABYLON.serialize()
  44938. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44939. __decorate([
  44940. BABYLON.serialize()
  44941. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44942. __decorate([
  44943. BABYLON.serialize()
  44944. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44945. __decorate([
  44946. BABYLON.serialize()
  44947. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44948. __decorate([
  44949. BABYLON.serialize()
  44950. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44951. __decorate([
  44952. BABYLON.serialize()
  44953. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44954. __decorate([
  44955. BABYLON.serialize()
  44956. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44957. __decorate([
  44958. BABYLON.serializeAsVector3()
  44959. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44960. __decorate([
  44961. BABYLON.serialize()
  44962. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44963. __decorate([
  44964. BABYLON.serialize()
  44965. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44966. __decorate([
  44967. BABYLON.serialize()
  44968. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44969. return ArcRotateCamera;
  44970. }(BABYLON.TargetCamera));
  44971. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44972. })(BABYLON || (BABYLON = {}));
  44973. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44974. var BABYLON;
  44975. (function (BABYLON) {
  44976. /**
  44977. * The HemisphericLight simulates the ambient environment light,
  44978. * so the passed direction is the light reflection direction, not the incoming direction.
  44979. */
  44980. var HemisphericLight = /** @class */ (function (_super) {
  44981. __extends(HemisphericLight, _super);
  44982. /**
  44983. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44984. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44985. * The HemisphericLight can't cast shadows.
  44986. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44987. * @param name The friendly name of the light
  44988. * @param direction The direction of the light reflection
  44989. * @param scene The scene the light belongs to
  44990. */
  44991. function HemisphericLight(name, direction, scene) {
  44992. var _this = _super.call(this, name, scene) || this;
  44993. /**
  44994. * The groundColor is the light in the opposite direction to the one specified during creation.
  44995. * 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.
  44996. */
  44997. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44998. _this.direction = direction || BABYLON.Vector3.Up();
  44999. return _this;
  45000. }
  45001. HemisphericLight.prototype._buildUniformLayout = function () {
  45002. this._uniformBuffer.addUniform("vLightData", 4);
  45003. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45004. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45005. this._uniformBuffer.addUniform("vLightGround", 3);
  45006. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45007. this._uniformBuffer.addUniform("depthValues", 2);
  45008. this._uniformBuffer.create();
  45009. };
  45010. /**
  45011. * Returns the string "HemisphericLight".
  45012. * @return The class name
  45013. */
  45014. HemisphericLight.prototype.getClassName = function () {
  45015. return "HemisphericLight";
  45016. };
  45017. /**
  45018. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45019. * Returns the updated direction.
  45020. * @param target The target the direction should point to
  45021. * @return The computed direction
  45022. */
  45023. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45024. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45025. return this.direction;
  45026. };
  45027. /**
  45028. * Returns the shadow generator associated to the light.
  45029. * @returns Always null for hemispheric lights because it does not support shadows.
  45030. */
  45031. HemisphericLight.prototype.getShadowGenerator = function () {
  45032. return null;
  45033. };
  45034. /**
  45035. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45036. * @param effect The effect to update
  45037. * @param lightIndex The index of the light in the effect to update
  45038. * @returns The hemispheric light
  45039. */
  45040. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45041. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45042. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45043. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45044. return this;
  45045. };
  45046. /**
  45047. * @ignore internal use only.
  45048. */
  45049. HemisphericLight.prototype._getWorldMatrix = function () {
  45050. if (!this._worldMatrix) {
  45051. this._worldMatrix = BABYLON.Matrix.Identity();
  45052. }
  45053. return this._worldMatrix;
  45054. };
  45055. /**
  45056. * Returns the integer 3.
  45057. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45058. */
  45059. HemisphericLight.prototype.getTypeID = function () {
  45060. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45061. };
  45062. __decorate([
  45063. BABYLON.serializeAsColor3()
  45064. ], HemisphericLight.prototype, "groundColor", void 0);
  45065. __decorate([
  45066. BABYLON.serializeAsVector3()
  45067. ], HemisphericLight.prototype, "direction", void 0);
  45068. return HemisphericLight;
  45069. }(BABYLON.Light));
  45070. BABYLON.HemisphericLight = HemisphericLight;
  45071. })(BABYLON || (BABYLON = {}));
  45072. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45073. var BABYLON;
  45074. (function (BABYLON) {
  45075. /**
  45076. * Base implementation of @see IShadowLight
  45077. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45078. */
  45079. var ShadowLight = /** @class */ (function (_super) {
  45080. __extends(ShadowLight, _super);
  45081. function ShadowLight() {
  45082. var _this = _super !== null && _super.apply(this, arguments) || this;
  45083. _this._needProjectionMatrixCompute = true;
  45084. return _this;
  45085. }
  45086. ShadowLight.prototype._setPosition = function (value) {
  45087. this._position = value;
  45088. };
  45089. Object.defineProperty(ShadowLight.prototype, "position", {
  45090. /**
  45091. * Sets the position the shadow will be casted from. Also use as the light position for both
  45092. * point and spot lights.
  45093. */
  45094. get: function () {
  45095. return this._position;
  45096. },
  45097. /**
  45098. * Sets the position the shadow will be casted from. Also use as the light position for both
  45099. * point and spot lights.
  45100. */
  45101. set: function (value) {
  45102. this._setPosition(value);
  45103. },
  45104. enumerable: true,
  45105. configurable: true
  45106. });
  45107. ShadowLight.prototype._setDirection = function (value) {
  45108. this._direction = value;
  45109. };
  45110. Object.defineProperty(ShadowLight.prototype, "direction", {
  45111. /**
  45112. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45113. * Also use as the light direction on spot and directional lights.
  45114. */
  45115. get: function () {
  45116. return this._direction;
  45117. },
  45118. /**
  45119. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45120. * Also use as the light direction on spot and directional lights.
  45121. */
  45122. set: function (value) {
  45123. this._setDirection(value);
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45129. /**
  45130. * Gets the shadow projection clipping minimum z value.
  45131. */
  45132. get: function () {
  45133. return this._shadowMinZ;
  45134. },
  45135. /**
  45136. * Sets the shadow projection clipping minimum z value.
  45137. */
  45138. set: function (value) {
  45139. this._shadowMinZ = value;
  45140. this.forceProjectionMatrixCompute();
  45141. },
  45142. enumerable: true,
  45143. configurable: true
  45144. });
  45145. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45146. /**
  45147. * Sets the shadow projection clipping maximum z value.
  45148. */
  45149. get: function () {
  45150. return this._shadowMaxZ;
  45151. },
  45152. /**
  45153. * Gets the shadow projection clipping maximum z value.
  45154. */
  45155. set: function (value) {
  45156. this._shadowMaxZ = value;
  45157. this.forceProjectionMatrixCompute();
  45158. },
  45159. enumerable: true,
  45160. configurable: true
  45161. });
  45162. /**
  45163. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45164. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45165. */
  45166. ShadowLight.prototype.computeTransformedInformation = function () {
  45167. if (this.parent && this.parent.getWorldMatrix) {
  45168. if (!this.transformedPosition) {
  45169. this.transformedPosition = BABYLON.Vector3.Zero();
  45170. }
  45171. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45172. // In case the direction is present.
  45173. if (this.direction) {
  45174. if (!this.transformedDirection) {
  45175. this.transformedDirection = BABYLON.Vector3.Zero();
  45176. }
  45177. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45178. }
  45179. return true;
  45180. }
  45181. return false;
  45182. };
  45183. /**
  45184. * Return the depth scale used for the shadow map.
  45185. * @returns the depth scale.
  45186. */
  45187. ShadowLight.prototype.getDepthScale = function () {
  45188. return 50.0;
  45189. };
  45190. /**
  45191. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45192. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45193. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45194. */
  45195. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45196. return this.transformedDirection ? this.transformedDirection : this.direction;
  45197. };
  45198. /**
  45199. * Returns the ShadowLight absolute position in the World.
  45200. * @returns the position vector in world space
  45201. */
  45202. ShadowLight.prototype.getAbsolutePosition = function () {
  45203. return this.transformedPosition ? this.transformedPosition : this.position;
  45204. };
  45205. /**
  45206. * Sets the ShadowLight direction toward the passed target.
  45207. * @param target The point tot target in local space
  45208. * @returns the updated ShadowLight direction
  45209. */
  45210. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45211. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45212. return this.direction;
  45213. };
  45214. /**
  45215. * Returns the light rotation in euler definition.
  45216. * @returns the x y z rotation in local space.
  45217. */
  45218. ShadowLight.prototype.getRotation = function () {
  45219. this.direction.normalize();
  45220. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45221. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45222. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45223. };
  45224. /**
  45225. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45226. * @returns true if a cube texture needs to be use
  45227. */
  45228. ShadowLight.prototype.needCube = function () {
  45229. return false;
  45230. };
  45231. /**
  45232. * Detects if the projection matrix requires to be recomputed this frame.
  45233. * @returns true if it requires to be recomputed otherwise, false.
  45234. */
  45235. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45236. return this._needProjectionMatrixCompute;
  45237. };
  45238. /**
  45239. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45240. */
  45241. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45242. this._needProjectionMatrixCompute = true;
  45243. };
  45244. /**
  45245. * Get the world matrix of the sahdow lights.
  45246. * @ignore Internal Use Only
  45247. */
  45248. ShadowLight.prototype._getWorldMatrix = function () {
  45249. if (!this._worldMatrix) {
  45250. this._worldMatrix = BABYLON.Matrix.Identity();
  45251. }
  45252. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45253. return this._worldMatrix;
  45254. };
  45255. /**
  45256. * Gets the minZ used for shadow according to both the scene and the light.
  45257. * @param activeCamera The camera we are returning the min for
  45258. * @returns the depth min z
  45259. */
  45260. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45261. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45262. };
  45263. /**
  45264. * Gets the maxZ used for shadow according to both the scene and the light.
  45265. * @param activeCamera The camera we are returning the max for
  45266. * @returns the depth max z
  45267. */
  45268. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45269. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45270. };
  45271. /**
  45272. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45273. * @param matrix The materix to updated with the projection information
  45274. * @param viewMatrix The transform matrix of the light
  45275. * @param renderList The list of mesh to render in the map
  45276. * @returns The current light
  45277. */
  45278. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45279. if (this.customProjectionMatrixBuilder) {
  45280. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45281. }
  45282. else {
  45283. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45284. }
  45285. return this;
  45286. };
  45287. __decorate([
  45288. BABYLON.serializeAsVector3()
  45289. ], ShadowLight.prototype, "position", null);
  45290. __decorate([
  45291. BABYLON.serializeAsVector3()
  45292. ], ShadowLight.prototype, "direction", null);
  45293. __decorate([
  45294. BABYLON.serialize()
  45295. ], ShadowLight.prototype, "shadowMinZ", null);
  45296. __decorate([
  45297. BABYLON.serialize()
  45298. ], ShadowLight.prototype, "shadowMaxZ", null);
  45299. return ShadowLight;
  45300. }(BABYLON.Light));
  45301. BABYLON.ShadowLight = ShadowLight;
  45302. })(BABYLON || (BABYLON = {}));
  45303. //# sourceMappingURL=babylon.shadowLight.js.map
  45304. var BABYLON;
  45305. (function (BABYLON) {
  45306. /**
  45307. * A point light is a light defined by an unique point in world space.
  45308. * The light is emitted in every direction from this point.
  45309. * A good example of a point light is a standard light bulb.
  45310. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45311. */
  45312. var PointLight = /** @class */ (function (_super) {
  45313. __extends(PointLight, _super);
  45314. /**
  45315. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45316. * A PointLight emits the light in every direction.
  45317. * It can cast shadows.
  45318. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45319. * ```javascript
  45320. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45321. * ```
  45322. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45323. * @param name The light friendly name
  45324. * @param position The position of the point light in the scene
  45325. * @param scene The scene the lights belongs to
  45326. */
  45327. function PointLight(name, position, scene) {
  45328. var _this = _super.call(this, name, scene) || this;
  45329. _this._shadowAngle = Math.PI / 2;
  45330. _this.position = position;
  45331. return _this;
  45332. }
  45333. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45334. /**
  45335. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45336. * This specifies what angle the shadow will use to be created.
  45337. *
  45338. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45339. */
  45340. get: function () {
  45341. return this._shadowAngle;
  45342. },
  45343. /**
  45344. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45345. * This specifies what angle the shadow will use to be created.
  45346. *
  45347. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45348. */
  45349. set: function (value) {
  45350. this._shadowAngle = value;
  45351. this.forceProjectionMatrixCompute();
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(PointLight.prototype, "direction", {
  45357. /**
  45358. * Gets the direction if it has been set.
  45359. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45360. */
  45361. get: function () {
  45362. return this._direction;
  45363. },
  45364. /**
  45365. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45366. */
  45367. set: function (value) {
  45368. var previousNeedCube = this.needCube();
  45369. this._direction = value;
  45370. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45371. this._shadowGenerator.recreateShadowMap();
  45372. }
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. /**
  45378. * Returns the string "PointLight"
  45379. * @returns the class name
  45380. */
  45381. PointLight.prototype.getClassName = function () {
  45382. return "PointLight";
  45383. };
  45384. /**
  45385. * Returns the integer 0.
  45386. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45387. */
  45388. PointLight.prototype.getTypeID = function () {
  45389. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45390. };
  45391. /**
  45392. * Specifies wether or not the shadowmap should be a cube texture.
  45393. * @returns true if the shadowmap needs to be a cube texture.
  45394. */
  45395. PointLight.prototype.needCube = function () {
  45396. return !this.direction;
  45397. };
  45398. /**
  45399. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45400. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45401. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45402. */
  45403. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45404. if (this.direction) {
  45405. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45406. }
  45407. else {
  45408. switch (faceIndex) {
  45409. case 0:
  45410. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45411. case 1:
  45412. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45413. case 2:
  45414. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45415. case 3:
  45416. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45417. case 4:
  45418. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45419. case 5:
  45420. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45421. }
  45422. }
  45423. return BABYLON.Vector3.Zero();
  45424. };
  45425. /**
  45426. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45427. * - fov = PI / 2
  45428. * - aspect ratio : 1.0
  45429. * - z-near and far equal to the active camera minZ and maxZ.
  45430. * Returns the PointLight.
  45431. */
  45432. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45433. var activeCamera = this.getScene().activeCamera;
  45434. if (!activeCamera) {
  45435. return;
  45436. }
  45437. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45438. };
  45439. PointLight.prototype._buildUniformLayout = function () {
  45440. this._uniformBuffer.addUniform("vLightData", 4);
  45441. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45442. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45443. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45444. this._uniformBuffer.addUniform("depthValues", 2);
  45445. this._uniformBuffer.create();
  45446. };
  45447. /**
  45448. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45449. * @param effect The effect to update
  45450. * @param lightIndex The index of the light in the effect to update
  45451. * @returns The point light
  45452. */
  45453. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45454. if (this.computeTransformedInformation()) {
  45455. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45456. return this;
  45457. }
  45458. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45459. return this;
  45460. };
  45461. __decorate([
  45462. BABYLON.serialize()
  45463. ], PointLight.prototype, "shadowAngle", null);
  45464. return PointLight;
  45465. }(BABYLON.ShadowLight));
  45466. BABYLON.PointLight = PointLight;
  45467. })(BABYLON || (BABYLON = {}));
  45468. //# sourceMappingURL=babylon.pointLight.js.map
  45469. var BABYLON;
  45470. (function (BABYLON) {
  45471. /**
  45472. * A directional light is defined by a direction (what a surprise!).
  45473. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45474. * 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.
  45475. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45476. */
  45477. var DirectionalLight = /** @class */ (function (_super) {
  45478. __extends(DirectionalLight, _super);
  45479. /**
  45480. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45481. * The directional light is emitted from everywhere in the given direction.
  45482. * It can cast shawdows.
  45483. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45484. * @param name The friendly name of the light
  45485. * @param direction The direction of the light
  45486. * @param scene The scene the light belongs to
  45487. */
  45488. function DirectionalLight(name, direction, scene) {
  45489. var _this = _super.call(this, name, scene) || this;
  45490. _this._shadowFrustumSize = 0;
  45491. _this._shadowOrthoScale = 0.5;
  45492. /**
  45493. * Automatically compute the projection matrix to best fit (including all the casters)
  45494. * on each frame.
  45495. */
  45496. _this.autoUpdateExtends = true;
  45497. // Cache
  45498. _this._orthoLeft = Number.MAX_VALUE;
  45499. _this._orthoRight = Number.MIN_VALUE;
  45500. _this._orthoTop = Number.MIN_VALUE;
  45501. _this._orthoBottom = Number.MAX_VALUE;
  45502. _this.position = direction.scale(-1.0);
  45503. _this.direction = direction;
  45504. return _this;
  45505. }
  45506. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45507. /**
  45508. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45509. */
  45510. get: function () {
  45511. return this._shadowFrustumSize;
  45512. },
  45513. /**
  45514. * Specifies a fix frustum size for the shadow generation.
  45515. */
  45516. set: function (value) {
  45517. this._shadowFrustumSize = value;
  45518. this.forceProjectionMatrixCompute();
  45519. },
  45520. enumerable: true,
  45521. configurable: true
  45522. });
  45523. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45524. /**
  45525. * Gets the shadow projection scale against the optimal computed one.
  45526. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45527. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45528. */
  45529. get: function () {
  45530. return this._shadowOrthoScale;
  45531. },
  45532. /**
  45533. * Sets the shadow projection scale against the optimal computed one.
  45534. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45535. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45536. */
  45537. set: function (value) {
  45538. this._shadowOrthoScale = value;
  45539. this.forceProjectionMatrixCompute();
  45540. },
  45541. enumerable: true,
  45542. configurable: true
  45543. });
  45544. /**
  45545. * Returns the string "DirectionalLight".
  45546. * @return The class name
  45547. */
  45548. DirectionalLight.prototype.getClassName = function () {
  45549. return "DirectionalLight";
  45550. };
  45551. /**
  45552. * Returns the integer 1.
  45553. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45554. */
  45555. DirectionalLight.prototype.getTypeID = function () {
  45556. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45557. };
  45558. /**
  45559. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45560. * Returns the DirectionalLight Shadow projection matrix.
  45561. */
  45562. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45563. if (this.shadowFrustumSize > 0) {
  45564. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45565. }
  45566. else {
  45567. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45568. }
  45569. };
  45570. /**
  45571. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45572. * Returns the DirectionalLight Shadow projection matrix.
  45573. */
  45574. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45575. var activeCamera = this.getScene().activeCamera;
  45576. if (!activeCamera) {
  45577. return;
  45578. }
  45579. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45580. };
  45581. /**
  45582. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45583. * Returns the DirectionalLight Shadow projection matrix.
  45584. */
  45585. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45586. var activeCamera = this.getScene().activeCamera;
  45587. if (!activeCamera) {
  45588. return;
  45589. }
  45590. // Check extends
  45591. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45592. var tempVector3 = BABYLON.Vector3.Zero();
  45593. this._orthoLeft = Number.MAX_VALUE;
  45594. this._orthoRight = Number.MIN_VALUE;
  45595. this._orthoTop = Number.MIN_VALUE;
  45596. this._orthoBottom = Number.MAX_VALUE;
  45597. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45598. var mesh = renderList[meshIndex];
  45599. if (!mesh) {
  45600. continue;
  45601. }
  45602. var boundingInfo = mesh.getBoundingInfo();
  45603. var boundingBox = boundingInfo.boundingBox;
  45604. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45605. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45606. if (tempVector3.x < this._orthoLeft)
  45607. this._orthoLeft = tempVector3.x;
  45608. if (tempVector3.y < this._orthoBottom)
  45609. this._orthoBottom = tempVector3.y;
  45610. if (tempVector3.x > this._orthoRight)
  45611. this._orthoRight = tempVector3.x;
  45612. if (tempVector3.y > this._orthoTop)
  45613. this._orthoTop = tempVector3.y;
  45614. }
  45615. }
  45616. }
  45617. var xOffset = this._orthoRight - this._orthoLeft;
  45618. var yOffset = this._orthoTop - this._orthoBottom;
  45619. 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);
  45620. };
  45621. DirectionalLight.prototype._buildUniformLayout = function () {
  45622. this._uniformBuffer.addUniform("vLightData", 4);
  45623. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45624. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45625. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45626. this._uniformBuffer.addUniform("depthValues", 2);
  45627. this._uniformBuffer.create();
  45628. };
  45629. /**
  45630. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45631. * @param effect The effect to update
  45632. * @param lightIndex The index of the light in the effect to update
  45633. * @returns The directional light
  45634. */
  45635. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45636. if (this.computeTransformedInformation()) {
  45637. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45638. return this;
  45639. }
  45640. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45641. return this;
  45642. };
  45643. /**
  45644. * Gets the minZ used for shadow according to both the scene and the light.
  45645. *
  45646. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45647. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45648. * @param activeCamera The camera we are returning the min for
  45649. * @returns the depth min z
  45650. */
  45651. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45652. return 1;
  45653. };
  45654. /**
  45655. * Gets the maxZ used for shadow according to both the scene and the light.
  45656. *
  45657. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45658. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45659. * @param activeCamera The camera we are returning the max for
  45660. * @returns the depth max z
  45661. */
  45662. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45663. return 1;
  45664. };
  45665. __decorate([
  45666. BABYLON.serialize()
  45667. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45668. __decorate([
  45669. BABYLON.serialize()
  45670. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45671. __decorate([
  45672. BABYLON.serialize()
  45673. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45674. return DirectionalLight;
  45675. }(BABYLON.ShadowLight));
  45676. BABYLON.DirectionalLight = DirectionalLight;
  45677. })(BABYLON || (BABYLON = {}));
  45678. //# sourceMappingURL=babylon.directionalLight.js.map
  45679. var BABYLON;
  45680. (function (BABYLON) {
  45681. /**
  45682. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45683. * These values define a cone of light starting from the position, emitting toward the direction.
  45684. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45685. * and the exponent defines the speed of the decay of the light with distance (reach).
  45686. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45687. */
  45688. var SpotLight = /** @class */ (function (_super) {
  45689. __extends(SpotLight, _super);
  45690. /**
  45691. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45692. * It can cast shadows.
  45693. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45694. * @param name The light friendly name
  45695. * @param position The position of the spot light in the scene
  45696. * @param direction The direction of the light in the scene
  45697. * @param angle The cone angle of the light in Radians
  45698. * @param exponent The light decay speed with the distance from the emission spot
  45699. * @param scene The scene the lights belongs to
  45700. */
  45701. function SpotLight(name, position, direction, angle, exponent, scene) {
  45702. var _this = _super.call(this, name, scene) || this;
  45703. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45704. _this._projectionTextureLightNear = 1e-6;
  45705. _this._projectionTextureLightFar = 1000.0;
  45706. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45707. _this._projectionTextureViewLightDirty = true;
  45708. _this._projectionTextureProjectionLightDirty = true;
  45709. _this._projectionTextureDirty = true;
  45710. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45711. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45712. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45713. _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);
  45714. _this.position = position;
  45715. _this.direction = direction;
  45716. _this.angle = angle;
  45717. _this.exponent = exponent;
  45718. return _this;
  45719. }
  45720. Object.defineProperty(SpotLight.prototype, "angle", {
  45721. /**
  45722. * Gets the cone angle of the spot light in Radians.
  45723. */
  45724. get: function () {
  45725. return this._angle;
  45726. },
  45727. /**
  45728. * Sets the cone angle of the spot light in Radians.
  45729. */
  45730. set: function (value) {
  45731. this._angle = value;
  45732. this._projectionTextureProjectionLightDirty = true;
  45733. this.forceProjectionMatrixCompute();
  45734. },
  45735. enumerable: true,
  45736. configurable: true
  45737. });
  45738. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45739. /**
  45740. * Allows scaling the angle of the light for shadow generation only.
  45741. */
  45742. get: function () {
  45743. return this._shadowAngleScale;
  45744. },
  45745. /**
  45746. * Allows scaling the angle of the light for shadow generation only.
  45747. */
  45748. set: function (value) {
  45749. this._shadowAngleScale = value;
  45750. this.forceProjectionMatrixCompute();
  45751. },
  45752. enumerable: true,
  45753. configurable: true
  45754. });
  45755. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45756. /**
  45757. * Allows reading the projecton texture
  45758. */
  45759. get: function () {
  45760. return this._projectionTextureMatrix;
  45761. },
  45762. enumerable: true,
  45763. configurable: true
  45764. });
  45765. ;
  45766. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45767. /**
  45768. * Gets the near clip of the Spotlight for texture projection.
  45769. */
  45770. get: function () {
  45771. return this._projectionTextureLightNear;
  45772. },
  45773. /**
  45774. * Sets the near clip of the Spotlight for texture projection.
  45775. */
  45776. set: function (value) {
  45777. this._projectionTextureLightNear = value;
  45778. this._projectionTextureProjectionLightDirty = true;
  45779. },
  45780. enumerable: true,
  45781. configurable: true
  45782. });
  45783. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45784. /**
  45785. * Gets the far clip of the Spotlight for texture projection.
  45786. */
  45787. get: function () {
  45788. return this._projectionTextureLightFar;
  45789. },
  45790. /**
  45791. * Sets the far clip of the Spotlight for texture projection.
  45792. */
  45793. set: function (value) {
  45794. this._projectionTextureLightFar = value;
  45795. this._projectionTextureProjectionLightDirty = true;
  45796. },
  45797. enumerable: true,
  45798. configurable: true
  45799. });
  45800. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45801. /**
  45802. * Gets the Up vector of the Spotlight for texture projection.
  45803. */
  45804. get: function () {
  45805. return this._projectionTextureUpDirection;
  45806. },
  45807. /**
  45808. * Sets the Up vector of the Spotlight for texture projection.
  45809. */
  45810. set: function (value) {
  45811. this._projectionTextureUpDirection = value;
  45812. this._projectionTextureProjectionLightDirty = true;
  45813. },
  45814. enumerable: true,
  45815. configurable: true
  45816. });
  45817. ;
  45818. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45819. /**
  45820. * Gets the projection texture of the light.
  45821. */
  45822. get: function () {
  45823. return this._projectionTexture;
  45824. },
  45825. /**
  45826. * Sets the projection texture of the light.
  45827. */
  45828. set: function (value) {
  45829. this._projectionTexture = value;
  45830. this._projectionTextureDirty = true;
  45831. },
  45832. enumerable: true,
  45833. configurable: true
  45834. });
  45835. /**
  45836. * Returns the string "SpotLight".
  45837. * @returns the class name
  45838. */
  45839. SpotLight.prototype.getClassName = function () {
  45840. return "SpotLight";
  45841. };
  45842. /**
  45843. * Returns the integer 2.
  45844. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45845. */
  45846. SpotLight.prototype.getTypeID = function () {
  45847. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45848. };
  45849. /**
  45850. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45851. */
  45852. SpotLight.prototype._setDirection = function (value) {
  45853. _super.prototype._setDirection.call(this, value);
  45854. this._projectionTextureViewLightDirty = true;
  45855. };
  45856. /**
  45857. * Overrides the position setter to recompute the projection texture view light Matrix.
  45858. */
  45859. SpotLight.prototype._setPosition = function (value) {
  45860. _super.prototype._setPosition.call(this, value);
  45861. this._projectionTextureViewLightDirty = true;
  45862. };
  45863. /**
  45864. * 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.
  45865. * Returns the SpotLight.
  45866. */
  45867. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45868. var activeCamera = this.getScene().activeCamera;
  45869. if (!activeCamera) {
  45870. return;
  45871. }
  45872. this._shadowAngleScale = this._shadowAngleScale || 1;
  45873. var angle = this._shadowAngleScale * this._angle;
  45874. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45875. };
  45876. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45877. this._projectionTextureViewLightDirty = false;
  45878. this._projectionTextureDirty = true;
  45879. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45880. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45881. };
  45882. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45883. this._projectionTextureProjectionLightDirty = false;
  45884. this._projectionTextureDirty = true;
  45885. var light_far = this.projectionTextureLightFar;
  45886. var light_near = this.projectionTextureLightNear;
  45887. var P = light_far / (light_far - light_near);
  45888. var Q = -P * light_near;
  45889. var S = 1.0 / Math.tan(this._angle / 2.0);
  45890. var A = 1.0;
  45891. 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);
  45892. };
  45893. /**
  45894. * Main function for light texture projection matrix computing.
  45895. */
  45896. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45897. this._projectionTextureDirty = false;
  45898. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45899. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45900. };
  45901. SpotLight.prototype._buildUniformLayout = function () {
  45902. this._uniformBuffer.addUniform("vLightData", 4);
  45903. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45904. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45905. this._uniformBuffer.addUniform("vLightDirection", 3);
  45906. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45907. this._uniformBuffer.addUniform("depthValues", 2);
  45908. this._uniformBuffer.create();
  45909. };
  45910. /**
  45911. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45912. * @param effect The effect to update
  45913. * @param lightIndex The index of the light in the effect to update
  45914. * @returns The spot light
  45915. */
  45916. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45917. var normalizeDirection;
  45918. if (this.computeTransformedInformation()) {
  45919. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45920. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45921. }
  45922. else {
  45923. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45924. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45925. }
  45926. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45927. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45928. if (this._projectionTextureViewLightDirty) {
  45929. this._computeProjectionTextureViewLightMatrix();
  45930. }
  45931. if (this._projectionTextureProjectionLightDirty) {
  45932. this._computeProjectionTextureProjectionLightMatrix();
  45933. }
  45934. if (this._projectionTextureDirty) {
  45935. this._computeProjectionTextureMatrix();
  45936. }
  45937. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45938. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45939. }
  45940. return this;
  45941. };
  45942. /**
  45943. * Disposes the light and the associated resources.
  45944. */
  45945. SpotLight.prototype.dispose = function () {
  45946. _super.prototype.dispose.call(this);
  45947. if (this._projectionTexture) {
  45948. this._projectionTexture.dispose();
  45949. }
  45950. };
  45951. __decorate([
  45952. BABYLON.serialize()
  45953. ], SpotLight.prototype, "angle", null);
  45954. __decorate([
  45955. BABYLON.serialize()
  45956. ], SpotLight.prototype, "shadowAngleScale", null);
  45957. __decorate([
  45958. BABYLON.serialize()
  45959. ], SpotLight.prototype, "exponent", void 0);
  45960. __decorate([
  45961. BABYLON.serialize()
  45962. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45963. __decorate([
  45964. BABYLON.serialize()
  45965. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45966. __decorate([
  45967. BABYLON.serialize()
  45968. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45969. __decorate([
  45970. BABYLON.serializeAsTexture("projectedLightTexture")
  45971. ], SpotLight.prototype, "_projectionTexture", void 0);
  45972. return SpotLight;
  45973. }(BABYLON.ShadowLight));
  45974. BABYLON.SpotLight = SpotLight;
  45975. })(BABYLON || (BABYLON = {}));
  45976. //# sourceMappingURL=babylon.spotLight.js.map
  45977. var BABYLON;
  45978. (function (BABYLON) {
  45979. var AnimationRange = /** @class */ (function () {
  45980. function AnimationRange(name, from, to) {
  45981. this.name = name;
  45982. this.from = from;
  45983. this.to = to;
  45984. }
  45985. AnimationRange.prototype.clone = function () {
  45986. return new AnimationRange(this.name, this.from, this.to);
  45987. };
  45988. return AnimationRange;
  45989. }());
  45990. BABYLON.AnimationRange = AnimationRange;
  45991. /**
  45992. * Composed of a frame, and an action function
  45993. */
  45994. var AnimationEvent = /** @class */ (function () {
  45995. function AnimationEvent(frame, action, onlyOnce) {
  45996. this.frame = frame;
  45997. this.action = action;
  45998. this.onlyOnce = onlyOnce;
  45999. this.isDone = false;
  46000. }
  46001. return AnimationEvent;
  46002. }());
  46003. BABYLON.AnimationEvent = AnimationEvent;
  46004. var PathCursor = /** @class */ (function () {
  46005. function PathCursor(path) {
  46006. this.path = path;
  46007. this._onchange = new Array();
  46008. this.value = 0;
  46009. this.animations = new Array();
  46010. }
  46011. PathCursor.prototype.getPoint = function () {
  46012. var point = this.path.getPointAtLengthPosition(this.value);
  46013. return new BABYLON.Vector3(point.x, 0, point.y);
  46014. };
  46015. PathCursor.prototype.moveAhead = function (step) {
  46016. if (step === void 0) { step = 0.002; }
  46017. this.move(step);
  46018. return this;
  46019. };
  46020. PathCursor.prototype.moveBack = function (step) {
  46021. if (step === void 0) { step = 0.002; }
  46022. this.move(-step);
  46023. return this;
  46024. };
  46025. PathCursor.prototype.move = function (step) {
  46026. if (Math.abs(step) > 1) {
  46027. throw "step size should be less than 1.";
  46028. }
  46029. this.value += step;
  46030. this.ensureLimits();
  46031. this.raiseOnChange();
  46032. return this;
  46033. };
  46034. PathCursor.prototype.ensureLimits = function () {
  46035. while (this.value > 1) {
  46036. this.value -= 1;
  46037. }
  46038. while (this.value < 0) {
  46039. this.value += 1;
  46040. }
  46041. return this;
  46042. };
  46043. // used by animation engine
  46044. PathCursor.prototype.raiseOnChange = function () {
  46045. var _this = this;
  46046. this._onchange.forEach(function (f) { return f(_this); });
  46047. return this;
  46048. };
  46049. PathCursor.prototype.onchange = function (f) {
  46050. this._onchange.push(f);
  46051. return this;
  46052. };
  46053. return PathCursor;
  46054. }());
  46055. BABYLON.PathCursor = PathCursor;
  46056. var AnimationKeyInterpolation;
  46057. (function (AnimationKeyInterpolation) {
  46058. /**
  46059. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46060. */
  46061. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46062. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46063. var Animation = /** @class */ (function () {
  46064. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46065. this.name = name;
  46066. this.targetProperty = targetProperty;
  46067. this.framePerSecond = framePerSecond;
  46068. this.dataType = dataType;
  46069. this.loopMode = loopMode;
  46070. this.enableBlending = enableBlending;
  46071. this._runtimeAnimations = new Array();
  46072. // The set of event that will be linked to this animation
  46073. this._events = new Array();
  46074. this.blendingSpeed = 0.01;
  46075. this._ranges = {};
  46076. this.targetPropertyPath = targetProperty.split(".");
  46077. this.dataType = dataType;
  46078. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46079. }
  46080. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46081. var dataType = undefined;
  46082. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46083. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46084. }
  46085. else if (from instanceof BABYLON.Quaternion) {
  46086. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46087. }
  46088. else if (from instanceof BABYLON.Vector3) {
  46089. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46090. }
  46091. else if (from instanceof BABYLON.Vector2) {
  46092. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46093. }
  46094. else if (from instanceof BABYLON.Color3) {
  46095. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46096. }
  46097. else if (from instanceof BABYLON.Size) {
  46098. dataType = Animation.ANIMATIONTYPE_SIZE;
  46099. }
  46100. if (dataType == undefined) {
  46101. return null;
  46102. }
  46103. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46104. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46105. animation.setKeys(keys);
  46106. if (easingFunction !== undefined) {
  46107. animation.setEasingFunction(easingFunction);
  46108. }
  46109. return animation;
  46110. };
  46111. /**
  46112. * Sets up an animation.
  46113. * @param property the property to animate
  46114. * @param animationType the animation type to apply
  46115. * @param easingFunction the easing function used in the animation
  46116. * @returns The created animation
  46117. */
  46118. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46119. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46120. animation.setEasingFunction(easingFunction);
  46121. return animation;
  46122. };
  46123. /**
  46124. * Create and start an animation on a node
  46125. * @param {string} name defines the name of the global animation that will be run on all nodes
  46126. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46127. * @param {string} targetProperty defines property to animate
  46128. * @param {number} framePerSecond defines the number of frame per second yo use
  46129. * @param {number} totalFrame defines the number of frames in total
  46130. * @param {any} from defines the initial value
  46131. * @param {any} to defines the final value
  46132. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46133. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46134. * @param onAnimationEnd defines the callback to call when animation end
  46135. * @returns the animatable created for this animation
  46136. */
  46137. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46138. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46139. if (!animation) {
  46140. return null;
  46141. }
  46142. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46143. };
  46144. /**
  46145. * Create and start an animation on a node and its descendants
  46146. * @param {string} name defines the name of the global animation that will be run on all nodes
  46147. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46148. * @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.
  46149. * @param {string} targetProperty defines property to animate
  46150. * @param {number} framePerSecond defines the number of frame per second yo use
  46151. * @param {number} totalFrame defines the number of frames in total
  46152. * @param {any} from defines the initial value
  46153. * @param {any} to defines the final value
  46154. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46155. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46156. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46157. * @returns the list of animatables created for all nodes
  46158. * @example https://www.babylonjs-playground.com/#MH0VLI
  46159. */
  46160. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46161. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46162. if (!animation) {
  46163. return null;
  46164. }
  46165. var scene = node.getScene();
  46166. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46167. };
  46168. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46169. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46170. if (!animation) {
  46171. return null;
  46172. }
  46173. node.animations.push(animation);
  46174. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46175. };
  46176. /**
  46177. * Transition property of the Camera to the target Value.
  46178. * @param property The property to transition
  46179. * @param targetValue The target Value of the property
  46180. * @param host The object where the property to animate belongs
  46181. * @param scene Scene used to run the animation
  46182. * @param frameRate Framerate (in frame/s) to use
  46183. * @param transition The transition type we want to use
  46184. * @param duration The duration of the animation, in milliseconds
  46185. * @param onAnimationEnd Call back trigger at the end of the animation.
  46186. */
  46187. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46188. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46189. if (duration <= 0) {
  46190. host[property] = targetValue;
  46191. if (onAnimationEnd) {
  46192. onAnimationEnd();
  46193. }
  46194. return null;
  46195. }
  46196. var endFrame = frameRate * (duration / 1000);
  46197. transition.setKeys([{
  46198. frame: 0,
  46199. value: host[property].clone ? host[property].clone() : host[property]
  46200. },
  46201. {
  46202. frame: endFrame,
  46203. value: targetValue
  46204. }]);
  46205. if (!host.animations) {
  46206. host.animations = [];
  46207. }
  46208. host.animations.push(transition);
  46209. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46210. animation.onAnimationEnd = onAnimationEnd;
  46211. return animation;
  46212. };
  46213. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46214. /**
  46215. * Return the array of runtime animations currently using this animation
  46216. */
  46217. get: function () {
  46218. return this._runtimeAnimations;
  46219. },
  46220. enumerable: true,
  46221. configurable: true
  46222. });
  46223. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46224. get: function () {
  46225. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46226. var runtimeAnimation = _a[_i];
  46227. if (!runtimeAnimation.isStopped) {
  46228. return true;
  46229. }
  46230. }
  46231. return false;
  46232. },
  46233. enumerable: true,
  46234. configurable: true
  46235. });
  46236. // Methods
  46237. /**
  46238. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46239. */
  46240. Animation.prototype.toString = function (fullDetails) {
  46241. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46242. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46243. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46244. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46245. if (fullDetails) {
  46246. ret += ", Ranges: {";
  46247. var first = true;
  46248. for (var name in this._ranges) {
  46249. if (first) {
  46250. ret += ", ";
  46251. first = false;
  46252. }
  46253. ret += name;
  46254. }
  46255. ret += "}";
  46256. }
  46257. return ret;
  46258. };
  46259. /**
  46260. * Add an event to this animation.
  46261. */
  46262. Animation.prototype.addEvent = function (event) {
  46263. this._events.push(event);
  46264. };
  46265. /**
  46266. * Remove all events found at the given frame
  46267. * @param frame
  46268. */
  46269. Animation.prototype.removeEvents = function (frame) {
  46270. for (var index = 0; index < this._events.length; index++) {
  46271. if (this._events[index].frame === frame) {
  46272. this._events.splice(index, 1);
  46273. index--;
  46274. }
  46275. }
  46276. };
  46277. Animation.prototype.getEvents = function () {
  46278. return this._events;
  46279. };
  46280. Animation.prototype.createRange = function (name, from, to) {
  46281. // check name not already in use; could happen for bones after serialized
  46282. if (!this._ranges[name]) {
  46283. this._ranges[name] = new AnimationRange(name, from, to);
  46284. }
  46285. };
  46286. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46287. if (deleteFrames === void 0) { deleteFrames = true; }
  46288. var range = this._ranges[name];
  46289. if (!range) {
  46290. return;
  46291. }
  46292. if (deleteFrames) {
  46293. var from = range.from;
  46294. var to = range.to;
  46295. // this loop MUST go high to low for multiple splices to work
  46296. for (var key = this._keys.length - 1; key >= 0; key--) {
  46297. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46298. this._keys.splice(key, 1);
  46299. }
  46300. }
  46301. }
  46302. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46303. };
  46304. Animation.prototype.getRange = function (name) {
  46305. return this._ranges[name];
  46306. };
  46307. Animation.prototype.getKeys = function () {
  46308. return this._keys;
  46309. };
  46310. Animation.prototype.getHighestFrame = function () {
  46311. var ret = 0;
  46312. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46313. if (ret < this._keys[key].frame) {
  46314. ret = this._keys[key].frame;
  46315. }
  46316. }
  46317. return ret;
  46318. };
  46319. Animation.prototype.getEasingFunction = function () {
  46320. return this._easingFunction;
  46321. };
  46322. Animation.prototype.setEasingFunction = function (easingFunction) {
  46323. this._easingFunction = easingFunction;
  46324. };
  46325. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46326. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46327. };
  46328. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46329. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46330. };
  46331. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46332. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46333. };
  46334. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46335. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46336. };
  46337. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46338. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46339. };
  46340. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46341. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46342. };
  46343. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46344. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46345. };
  46346. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46347. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46348. };
  46349. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46350. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46351. };
  46352. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46353. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46354. };
  46355. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46356. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46357. };
  46358. Animation.prototype.clone = function () {
  46359. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46360. clone.enableBlending = this.enableBlending;
  46361. clone.blendingSpeed = this.blendingSpeed;
  46362. if (this._keys) {
  46363. clone.setKeys(this._keys);
  46364. }
  46365. if (this._ranges) {
  46366. clone._ranges = {};
  46367. for (var name in this._ranges) {
  46368. var range = this._ranges[name];
  46369. if (!range) {
  46370. continue;
  46371. }
  46372. clone._ranges[name] = range.clone();
  46373. }
  46374. }
  46375. return clone;
  46376. };
  46377. Animation.prototype.setKeys = function (values) {
  46378. this._keys = values.slice(0);
  46379. };
  46380. Animation.prototype.serialize = function () {
  46381. var serializationObject = {};
  46382. serializationObject.name = this.name;
  46383. serializationObject.property = this.targetProperty;
  46384. serializationObject.framePerSecond = this.framePerSecond;
  46385. serializationObject.dataType = this.dataType;
  46386. serializationObject.loopBehavior = this.loopMode;
  46387. serializationObject.enableBlending = this.enableBlending;
  46388. serializationObject.blendingSpeed = this.blendingSpeed;
  46389. var dataType = this.dataType;
  46390. serializationObject.keys = [];
  46391. var keys = this.getKeys();
  46392. for (var index = 0; index < keys.length; index++) {
  46393. var animationKey = keys[index];
  46394. var key = {};
  46395. key.frame = animationKey.frame;
  46396. switch (dataType) {
  46397. case Animation.ANIMATIONTYPE_FLOAT:
  46398. key.values = [animationKey.value];
  46399. break;
  46400. case Animation.ANIMATIONTYPE_QUATERNION:
  46401. case Animation.ANIMATIONTYPE_MATRIX:
  46402. case Animation.ANIMATIONTYPE_VECTOR3:
  46403. case Animation.ANIMATIONTYPE_COLOR3:
  46404. key.values = animationKey.value.asArray();
  46405. break;
  46406. }
  46407. serializationObject.keys.push(key);
  46408. }
  46409. serializationObject.ranges = [];
  46410. for (var name in this._ranges) {
  46411. var source = this._ranges[name];
  46412. if (!source) {
  46413. continue;
  46414. }
  46415. var range = {};
  46416. range.name = name;
  46417. range.from = source.from;
  46418. range.to = source.to;
  46419. serializationObject.ranges.push(range);
  46420. }
  46421. return serializationObject;
  46422. };
  46423. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46424. get: function () {
  46425. return Animation._ANIMATIONTYPE_FLOAT;
  46426. },
  46427. enumerable: true,
  46428. configurable: true
  46429. });
  46430. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46431. get: function () {
  46432. return Animation._ANIMATIONTYPE_VECTOR3;
  46433. },
  46434. enumerable: true,
  46435. configurable: true
  46436. });
  46437. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46438. get: function () {
  46439. return Animation._ANIMATIONTYPE_VECTOR2;
  46440. },
  46441. enumerable: true,
  46442. configurable: true
  46443. });
  46444. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46445. get: function () {
  46446. return Animation._ANIMATIONTYPE_SIZE;
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46452. get: function () {
  46453. return Animation._ANIMATIONTYPE_QUATERNION;
  46454. },
  46455. enumerable: true,
  46456. configurable: true
  46457. });
  46458. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46459. get: function () {
  46460. return Animation._ANIMATIONTYPE_MATRIX;
  46461. },
  46462. enumerable: true,
  46463. configurable: true
  46464. });
  46465. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46466. get: function () {
  46467. return Animation._ANIMATIONTYPE_COLOR3;
  46468. },
  46469. enumerable: true,
  46470. configurable: true
  46471. });
  46472. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46473. get: function () {
  46474. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46475. },
  46476. enumerable: true,
  46477. configurable: true
  46478. });
  46479. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46480. get: function () {
  46481. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46482. },
  46483. enumerable: true,
  46484. configurable: true
  46485. });
  46486. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46487. get: function () {
  46488. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46489. },
  46490. enumerable: true,
  46491. configurable: true
  46492. });
  46493. Animation.Parse = function (parsedAnimation) {
  46494. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46495. var dataType = parsedAnimation.dataType;
  46496. var keys = [];
  46497. var data;
  46498. var index;
  46499. if (parsedAnimation.enableBlending) {
  46500. animation.enableBlending = parsedAnimation.enableBlending;
  46501. }
  46502. if (parsedAnimation.blendingSpeed) {
  46503. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46504. }
  46505. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46506. var key = parsedAnimation.keys[index];
  46507. var inTangent;
  46508. var outTangent;
  46509. switch (dataType) {
  46510. case Animation.ANIMATIONTYPE_FLOAT:
  46511. data = key.values[0];
  46512. if (key.values.length >= 1) {
  46513. inTangent = key.values[1];
  46514. }
  46515. if (key.values.length >= 2) {
  46516. outTangent = key.values[2];
  46517. }
  46518. break;
  46519. case Animation.ANIMATIONTYPE_QUATERNION:
  46520. data = BABYLON.Quaternion.FromArray(key.values);
  46521. if (key.values.length >= 8) {
  46522. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46523. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46524. inTangent = _inTangent;
  46525. }
  46526. }
  46527. if (key.values.length >= 12) {
  46528. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46529. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46530. outTangent = _outTangent;
  46531. }
  46532. }
  46533. break;
  46534. case Animation.ANIMATIONTYPE_MATRIX:
  46535. data = BABYLON.Matrix.FromArray(key.values);
  46536. break;
  46537. case Animation.ANIMATIONTYPE_COLOR3:
  46538. data = BABYLON.Color3.FromArray(key.values);
  46539. break;
  46540. case Animation.ANIMATIONTYPE_VECTOR3:
  46541. default:
  46542. data = BABYLON.Vector3.FromArray(key.values);
  46543. break;
  46544. }
  46545. var keyData = {};
  46546. keyData.frame = key.frame;
  46547. keyData.value = data;
  46548. if (inTangent != undefined) {
  46549. keyData.inTangent = inTangent;
  46550. }
  46551. if (outTangent != undefined) {
  46552. keyData.outTangent = outTangent;
  46553. }
  46554. keys.push(keyData);
  46555. }
  46556. animation.setKeys(keys);
  46557. if (parsedAnimation.ranges) {
  46558. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46559. data = parsedAnimation.ranges[index];
  46560. animation.createRange(data.name, data.from, data.to);
  46561. }
  46562. }
  46563. return animation;
  46564. };
  46565. Animation.AppendSerializedAnimations = function (source, destination) {
  46566. if (source.animations) {
  46567. destination.animations = [];
  46568. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46569. var animation = source.animations[animationIndex];
  46570. destination.animations.push(animation.serialize());
  46571. }
  46572. }
  46573. };
  46574. Animation.AllowMatricesInterpolation = false;
  46575. // Statics
  46576. Animation._ANIMATIONTYPE_FLOAT = 0;
  46577. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46578. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46579. Animation._ANIMATIONTYPE_MATRIX = 3;
  46580. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46581. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46582. Animation._ANIMATIONTYPE_SIZE = 6;
  46583. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46584. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46585. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46586. return Animation;
  46587. }());
  46588. BABYLON.Animation = Animation;
  46589. })(BABYLON || (BABYLON = {}));
  46590. //# sourceMappingURL=babylon.animation.js.map
  46591. var BABYLON;
  46592. (function (BABYLON) {
  46593. /**
  46594. * This class defines the direct association between an animation and a target
  46595. */
  46596. var TargetedAnimation = /** @class */ (function () {
  46597. function TargetedAnimation() {
  46598. }
  46599. return TargetedAnimation;
  46600. }());
  46601. BABYLON.TargetedAnimation = TargetedAnimation;
  46602. /**
  46603. * Use this class to create coordinated animations on multiple targets
  46604. */
  46605. var AnimationGroup = /** @class */ (function () {
  46606. function AnimationGroup(name, scene) {
  46607. if (scene === void 0) { scene = null; }
  46608. this.name = name;
  46609. this._targetedAnimations = new Array();
  46610. this._animatables = new Array();
  46611. this._from = Number.MAX_VALUE;
  46612. this._to = -Number.MAX_VALUE;
  46613. this._speedRatio = 1;
  46614. this.onAnimationEndObservable = new BABYLON.Observable();
  46615. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46616. this._scene.animationGroups.push(this);
  46617. }
  46618. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46619. /**
  46620. * Define if the animations are started
  46621. */
  46622. get: function () {
  46623. return this._isStarted;
  46624. },
  46625. enumerable: true,
  46626. configurable: true
  46627. });
  46628. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46629. /**
  46630. * Gets or sets the speed ratio to use for all animations
  46631. */
  46632. get: function () {
  46633. return this._speedRatio;
  46634. },
  46635. /**
  46636. * Gets or sets the speed ratio to use for all animations
  46637. */
  46638. set: function (value) {
  46639. if (this._speedRatio === value) {
  46640. return;
  46641. }
  46642. this._speedRatio = value;
  46643. for (var index = 0; index < this._animatables.length; index++) {
  46644. var animatable = this._animatables[index];
  46645. animatable.speedRatio = this._speedRatio;
  46646. }
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46652. /**
  46653. * Gets the targeted animations for this animation group
  46654. */
  46655. get: function () {
  46656. return this._targetedAnimations;
  46657. },
  46658. enumerable: true,
  46659. configurable: true
  46660. });
  46661. /**
  46662. * Add an animation (with its target) in the group
  46663. * @param animation defines the animation we want to add
  46664. * @param target defines the target of the animation
  46665. * @returns the {BABYLON.TargetedAnimation} object
  46666. */
  46667. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46668. var targetedAnimation = {
  46669. animation: animation,
  46670. target: target
  46671. };
  46672. var keys = animation.getKeys();
  46673. if (this._from > keys[0].frame) {
  46674. this._from = keys[0].frame;
  46675. }
  46676. if (this._to < keys[keys.length - 1].frame) {
  46677. this._to = keys[keys.length - 1].frame;
  46678. }
  46679. this._targetedAnimations.push(targetedAnimation);
  46680. return targetedAnimation;
  46681. };
  46682. /**
  46683. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46684. * It can add constant keys at begin or end
  46685. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46686. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46687. */
  46688. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46689. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46690. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46691. beginFrame = Math.max(beginFrame, this._from);
  46692. endFrame = Math.min(endFrame, this._to);
  46693. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46694. var targetedAnimation = this._targetedAnimations[index];
  46695. var keys = targetedAnimation.animation.getKeys();
  46696. var startKey = keys[0];
  46697. var endKey = keys[keys.length - 1];
  46698. if (startKey.frame > beginFrame) {
  46699. var newKey = {
  46700. frame: beginFrame,
  46701. value: startKey.value,
  46702. inTangent: startKey.inTangent,
  46703. outTangent: startKey.outTangent,
  46704. interpolation: startKey.interpolation
  46705. };
  46706. keys.splice(0, 0, newKey);
  46707. }
  46708. if (endKey.frame < endFrame) {
  46709. var newKey = {
  46710. frame: endFrame,
  46711. value: endKey.value,
  46712. inTangent: endKey.outTangent,
  46713. outTangent: endKey.outTangent,
  46714. interpolation: endKey.interpolation
  46715. };
  46716. keys.push(newKey);
  46717. }
  46718. }
  46719. return this;
  46720. };
  46721. /**
  46722. * Start all animations on given targets
  46723. * @param loop defines if animations must loop
  46724. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46725. */
  46726. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46727. var _this = this;
  46728. if (loop === void 0) { loop = false; }
  46729. if (speedRatio === void 0) { speedRatio = 1; }
  46730. if (this._isStarted || this._targetedAnimations.length === 0) {
  46731. return this;
  46732. }
  46733. var _loop_1 = function () {
  46734. var targetedAnimation = this_1._targetedAnimations[index];
  46735. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46736. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46737. }));
  46738. };
  46739. var this_1 = this;
  46740. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46741. _loop_1();
  46742. }
  46743. this._speedRatio = speedRatio;
  46744. this._isStarted = true;
  46745. return this;
  46746. };
  46747. /**
  46748. * Pause all animations
  46749. */
  46750. AnimationGroup.prototype.pause = function () {
  46751. if (!this._isStarted) {
  46752. return this;
  46753. }
  46754. for (var index = 0; index < this._animatables.length; index++) {
  46755. var animatable = this._animatables[index];
  46756. animatable.pause();
  46757. }
  46758. return this;
  46759. };
  46760. /**
  46761. * Play all animations to initial state
  46762. * This function will start() the animations if they were not started or will restart() them if they were paused
  46763. * @param loop defines if animations must loop
  46764. */
  46765. AnimationGroup.prototype.play = function (loop) {
  46766. if (this.isStarted) {
  46767. if (loop !== undefined) {
  46768. for (var index = 0; index < this._animatables.length; index++) {
  46769. var animatable = this._animatables[index];
  46770. animatable.loopAnimation = loop;
  46771. }
  46772. }
  46773. this.restart();
  46774. }
  46775. else {
  46776. this.start(loop, this._speedRatio);
  46777. }
  46778. return this;
  46779. };
  46780. /**
  46781. * Reset all animations to initial state
  46782. */
  46783. AnimationGroup.prototype.reset = function () {
  46784. if (!this._isStarted) {
  46785. return this;
  46786. }
  46787. for (var index = 0; index < this._animatables.length; index++) {
  46788. var animatable = this._animatables[index];
  46789. animatable.reset();
  46790. }
  46791. return this;
  46792. };
  46793. /**
  46794. * Restart animations from key 0
  46795. */
  46796. AnimationGroup.prototype.restart = function () {
  46797. if (!this._isStarted) {
  46798. return this;
  46799. }
  46800. for (var index = 0; index < this._animatables.length; index++) {
  46801. var animatable = this._animatables[index];
  46802. animatable.restart();
  46803. }
  46804. return this;
  46805. };
  46806. /**
  46807. * Stop all animations
  46808. */
  46809. AnimationGroup.prototype.stop = function () {
  46810. if (!this._isStarted) {
  46811. return this;
  46812. }
  46813. for (var index = 0; index < this._animatables.length; index++) {
  46814. var animatable = this._animatables[index];
  46815. animatable.stop();
  46816. }
  46817. this._isStarted = false;
  46818. return this;
  46819. };
  46820. /**
  46821. * Dispose all associated resources
  46822. */
  46823. AnimationGroup.prototype.dispose = function () {
  46824. this._targetedAnimations = [];
  46825. this._animatables = [];
  46826. var index = this._scene.animationGroups.indexOf(this);
  46827. if (index > -1) {
  46828. this._scene.animationGroups.splice(index, 1);
  46829. }
  46830. };
  46831. return AnimationGroup;
  46832. }());
  46833. BABYLON.AnimationGroup = AnimationGroup;
  46834. })(BABYLON || (BABYLON = {}));
  46835. //# sourceMappingURL=babylon.animationGroup.js.map
  46836. var BABYLON;
  46837. (function (BABYLON) {
  46838. var RuntimeAnimation = /** @class */ (function () {
  46839. function RuntimeAnimation(target, animation) {
  46840. this._offsetsCache = {};
  46841. this._highLimitsCache = {};
  46842. this._stopped = false;
  46843. this._blendingFactor = 0;
  46844. this._ratioOffset = 0;
  46845. this._animation = animation;
  46846. this._target = target;
  46847. animation._runtimeAnimations.push(this);
  46848. }
  46849. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46850. get: function () {
  46851. return this._animation;
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. RuntimeAnimation.prototype.reset = function () {
  46857. this._offsetsCache = {};
  46858. this._highLimitsCache = {};
  46859. this.currentFrame = 0;
  46860. this._blendingFactor = 0;
  46861. this._originalBlendValue = null;
  46862. };
  46863. RuntimeAnimation.prototype.isStopped = function () {
  46864. return this._stopped;
  46865. };
  46866. RuntimeAnimation.prototype.dispose = function () {
  46867. var index = this._animation.runtimeAnimations.indexOf(this);
  46868. if (index > -1) {
  46869. this._animation.runtimeAnimations.splice(index, 1);
  46870. }
  46871. };
  46872. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46873. if (typeof value === "function") {
  46874. return value();
  46875. }
  46876. return value;
  46877. };
  46878. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46879. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46880. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46881. }
  46882. this.currentFrame = currentFrame;
  46883. var keys = this._animation.getKeys();
  46884. // Try to get a hash to find the right key
  46885. 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));
  46886. if (keys[startKeyIndex].frame >= currentFrame) {
  46887. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46888. startKeyIndex--;
  46889. }
  46890. }
  46891. for (var key = startKeyIndex; key < keys.length; key++) {
  46892. var endKey = keys[key + 1];
  46893. if (endKey.frame >= currentFrame) {
  46894. var startKey = keys[key];
  46895. var startValue = this._getKeyValue(startKey.value);
  46896. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46897. return startValue;
  46898. }
  46899. var endValue = this._getKeyValue(endKey.value);
  46900. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46901. var frameDelta = endKey.frame - startKey.frame;
  46902. // gradient : percent of currentFrame between the frame inf and the frame sup
  46903. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46904. // check for easingFunction and correction of gradient
  46905. var easingFunction = this._animation.getEasingFunction();
  46906. if (easingFunction != null) {
  46907. gradient = easingFunction.ease(gradient);
  46908. }
  46909. switch (this._animation.dataType) {
  46910. // Float
  46911. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46912. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46913. switch (loopMode) {
  46914. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46915. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46916. return floatValue;
  46917. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46918. return offsetValue * repeatCount + floatValue;
  46919. }
  46920. break;
  46921. // Quaternion
  46922. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46923. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46924. switch (loopMode) {
  46925. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46926. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46927. return quatValue;
  46928. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46929. return quatValue.add(offsetValue.scale(repeatCount));
  46930. }
  46931. return quatValue;
  46932. // Vector3
  46933. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46934. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46935. switch (loopMode) {
  46936. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46937. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46938. return vec3Value;
  46939. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46940. return vec3Value.add(offsetValue.scale(repeatCount));
  46941. }
  46942. // Vector2
  46943. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46944. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46945. switch (loopMode) {
  46946. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46947. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46948. return vec2Value;
  46949. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46950. return vec2Value.add(offsetValue.scale(repeatCount));
  46951. }
  46952. // Size
  46953. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46954. switch (loopMode) {
  46955. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46956. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46957. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46958. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46959. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46960. }
  46961. // Color3
  46962. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46963. switch (loopMode) {
  46964. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46965. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46966. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46967. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46968. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46969. }
  46970. // Matrix
  46971. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46972. switch (loopMode) {
  46973. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46974. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46975. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46976. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46977. }
  46978. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46979. return startValue;
  46980. }
  46981. default:
  46982. break;
  46983. }
  46984. break;
  46985. }
  46986. }
  46987. return this._getKeyValue(keys[keys.length - 1].value);
  46988. };
  46989. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46990. if (blend === void 0) { blend = false; }
  46991. // Set value
  46992. var path;
  46993. var destination;
  46994. var targetPropertyPath = this._animation.targetPropertyPath;
  46995. if (targetPropertyPath.length > 1) {
  46996. var property = this._target[targetPropertyPath[0]];
  46997. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46998. property = property[targetPropertyPath[index]];
  46999. }
  47000. path = targetPropertyPath[targetPropertyPath.length - 1];
  47001. destination = property;
  47002. }
  47003. else {
  47004. path = targetPropertyPath[0];
  47005. destination = this._target;
  47006. }
  47007. // Blending
  47008. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  47009. if (!this._originalBlendValue) {
  47010. if (destination[path].clone) {
  47011. this._originalBlendValue = destination[path].clone();
  47012. }
  47013. else {
  47014. this._originalBlendValue = destination[path];
  47015. }
  47016. }
  47017. if (this._originalBlendValue.prototype) {
  47018. if (this._originalBlendValue.prototype.Lerp) {
  47019. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47020. }
  47021. else {
  47022. destination[path] = currentValue;
  47023. }
  47024. }
  47025. else if (this._originalBlendValue.m) {
  47026. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47027. }
  47028. else {
  47029. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47030. }
  47031. this._blendingFactor += this._animation.blendingSpeed;
  47032. }
  47033. else {
  47034. destination[path] = currentValue;
  47035. }
  47036. if (this._target.markAsDirty) {
  47037. this._target.markAsDirty(this._animation.targetProperty);
  47038. }
  47039. };
  47040. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47041. var keys = this._animation.getKeys();
  47042. if (frame < keys[0].frame) {
  47043. frame = keys[0].frame;
  47044. }
  47045. else if (frame > keys[keys.length - 1].frame) {
  47046. frame = keys[keys.length - 1].frame;
  47047. }
  47048. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  47049. this.setValue(currentValue);
  47050. };
  47051. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47052. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47053. this._ratioOffset = this._previousRatio - newRatio;
  47054. };
  47055. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47056. if (blend === void 0) { blend = false; }
  47057. var targetPropertyPath = this._animation.targetPropertyPath;
  47058. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47059. this._stopped = true;
  47060. return false;
  47061. }
  47062. var returnValue = true;
  47063. var keys = this._animation.getKeys();
  47064. // Adding a start key at frame 0 if missing
  47065. if (keys[0].frame !== 0) {
  47066. var newKey = { frame: 0, value: keys[0].value };
  47067. keys.splice(0, 0, newKey);
  47068. }
  47069. // Check limits
  47070. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47071. from = keys[0].frame;
  47072. }
  47073. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47074. to = keys[keys.length - 1].frame;
  47075. }
  47076. //to and from cannot be the same key
  47077. if (from === to) {
  47078. if (from > keys[0].frame) {
  47079. from--;
  47080. }
  47081. else if (to < keys[keys.length - 1].frame) {
  47082. to++;
  47083. }
  47084. }
  47085. // Compute ratio
  47086. var range = to - from;
  47087. var offsetValue;
  47088. // ratio represents the frame delta between from and to
  47089. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47090. var highLimitValue = 0;
  47091. this._previousDelay = delay;
  47092. this._previousRatio = ratio;
  47093. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47094. returnValue = false;
  47095. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47096. }
  47097. else {
  47098. // Get max value if required
  47099. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47100. var keyOffset = to.toString() + from.toString();
  47101. if (!this._offsetsCache[keyOffset]) {
  47102. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47103. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47104. switch (this._animation.dataType) {
  47105. // Float
  47106. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47107. this._offsetsCache[keyOffset] = toValue - fromValue;
  47108. break;
  47109. // Quaternion
  47110. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47111. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47112. break;
  47113. // Vector3
  47114. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47115. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47116. // Vector2
  47117. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47119. // Size
  47120. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47121. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47122. // Color3
  47123. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47124. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47125. default:
  47126. break;
  47127. }
  47128. this._highLimitsCache[keyOffset] = toValue;
  47129. }
  47130. highLimitValue = this._highLimitsCache[keyOffset];
  47131. offsetValue = this._offsetsCache[keyOffset];
  47132. }
  47133. }
  47134. if (offsetValue === undefined) {
  47135. switch (this._animation.dataType) {
  47136. // Float
  47137. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47138. offsetValue = 0;
  47139. break;
  47140. // Quaternion
  47141. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47142. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47143. break;
  47144. // Vector3
  47145. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47146. offsetValue = BABYLON.Vector3.Zero();
  47147. break;
  47148. // Vector2
  47149. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47150. offsetValue = BABYLON.Vector2.Zero();
  47151. break;
  47152. // Size
  47153. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47154. offsetValue = BABYLON.Size.Zero();
  47155. break;
  47156. // Color3
  47157. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47158. offsetValue = BABYLON.Color3.Black();
  47159. }
  47160. }
  47161. // Compute value
  47162. var repeatCount = (ratio / range) >> 0;
  47163. var currentFrame = returnValue ? from + ratio % range : to;
  47164. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  47165. // Set value
  47166. this.setValue(currentValue);
  47167. // Check events
  47168. var events = this._animation.getEvents();
  47169. for (var index = 0; index < events.length; index++) {
  47170. // Make sure current frame has passed event frame and that event frame is within the current range
  47171. // Also, handle both forward and reverse animations
  47172. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47173. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47174. var event = events[index];
  47175. if (!event.isDone) {
  47176. // If event should be done only once, remove it.
  47177. if (event.onlyOnce) {
  47178. events.splice(index, 1);
  47179. index--;
  47180. }
  47181. event.isDone = true;
  47182. event.action();
  47183. } // Don't do anything if the event has already be done.
  47184. }
  47185. else if (events[index].isDone && !events[index].onlyOnce) {
  47186. // reset event, the animation is looping
  47187. events[index].isDone = false;
  47188. }
  47189. }
  47190. if (!returnValue) {
  47191. this._stopped = true;
  47192. }
  47193. return returnValue;
  47194. };
  47195. return RuntimeAnimation;
  47196. }());
  47197. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47198. })(BABYLON || (BABYLON = {}));
  47199. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47200. var BABYLON;
  47201. (function (BABYLON) {
  47202. var Animatable = /** @class */ (function () {
  47203. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47204. if (fromFrame === void 0) { fromFrame = 0; }
  47205. if (toFrame === void 0) { toFrame = 100; }
  47206. if (loopAnimation === void 0) { loopAnimation = false; }
  47207. if (speedRatio === void 0) { speedRatio = 1.0; }
  47208. this.target = target;
  47209. this.fromFrame = fromFrame;
  47210. this.toFrame = toFrame;
  47211. this.loopAnimation = loopAnimation;
  47212. this.onAnimationEnd = onAnimationEnd;
  47213. this._localDelayOffset = null;
  47214. this._pausedDelay = null;
  47215. this._runtimeAnimations = new Array();
  47216. this._paused = false;
  47217. this._speedRatio = 1;
  47218. this.animationStarted = false;
  47219. if (animations) {
  47220. this.appendAnimations(target, animations);
  47221. }
  47222. this._speedRatio = speedRatio;
  47223. this._scene = scene;
  47224. scene._activeAnimatables.push(this);
  47225. }
  47226. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47227. get: function () {
  47228. return this._speedRatio;
  47229. },
  47230. set: function (value) {
  47231. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47232. var animation = this._runtimeAnimations[index];
  47233. animation._prepareForSpeedRatioChange(value);
  47234. }
  47235. this._speedRatio = value;
  47236. },
  47237. enumerable: true,
  47238. configurable: true
  47239. });
  47240. // Methods
  47241. Animatable.prototype.getAnimations = function () {
  47242. return this._runtimeAnimations;
  47243. };
  47244. Animatable.prototype.appendAnimations = function (target, animations) {
  47245. for (var index = 0; index < animations.length; index++) {
  47246. var animation = animations[index];
  47247. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47248. }
  47249. };
  47250. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47251. var runtimeAnimations = this._runtimeAnimations;
  47252. for (var index = 0; index < runtimeAnimations.length; index++) {
  47253. if (runtimeAnimations[index].animation.targetProperty === property) {
  47254. return runtimeAnimations[index].animation;
  47255. }
  47256. }
  47257. return null;
  47258. };
  47259. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47260. var runtimeAnimations = this._runtimeAnimations;
  47261. for (var index = 0; index < runtimeAnimations.length; index++) {
  47262. if (runtimeAnimations[index].animation.targetProperty === property) {
  47263. return runtimeAnimations[index];
  47264. }
  47265. }
  47266. return null;
  47267. };
  47268. Animatable.prototype.reset = function () {
  47269. var runtimeAnimations = this._runtimeAnimations;
  47270. for (var index = 0; index < runtimeAnimations.length; index++) {
  47271. runtimeAnimations[index].reset();
  47272. }
  47273. // Reset to original value
  47274. for (index = 0; index < runtimeAnimations.length; index++) {
  47275. var animation = runtimeAnimations[index];
  47276. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47277. }
  47278. this._localDelayOffset = null;
  47279. this._pausedDelay = null;
  47280. };
  47281. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47282. var runtimeAnimations = this._runtimeAnimations;
  47283. for (var index = 0; index < runtimeAnimations.length; index++) {
  47284. runtimeAnimations[index].animation.enableBlending = true;
  47285. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47286. }
  47287. };
  47288. Animatable.prototype.disableBlending = function () {
  47289. var runtimeAnimations = this._runtimeAnimations;
  47290. for (var index = 0; index < runtimeAnimations.length; index++) {
  47291. runtimeAnimations[index].animation.enableBlending = false;
  47292. }
  47293. };
  47294. Animatable.prototype.goToFrame = function (frame) {
  47295. var runtimeAnimations = this._runtimeAnimations;
  47296. if (runtimeAnimations[0]) {
  47297. var fps = runtimeAnimations[0].animation.framePerSecond;
  47298. var currentFrame = runtimeAnimations[0].currentFrame;
  47299. var adjustTime = frame - currentFrame;
  47300. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47301. if (this._localDelayOffset === null) {
  47302. this._localDelayOffset = 0;
  47303. }
  47304. this._localDelayOffset -= delay;
  47305. }
  47306. for (var index = 0; index < runtimeAnimations.length; index++) {
  47307. runtimeAnimations[index].goToFrame(frame);
  47308. }
  47309. };
  47310. Animatable.prototype.pause = function () {
  47311. if (this._paused) {
  47312. return;
  47313. }
  47314. this._paused = true;
  47315. };
  47316. Animatable.prototype.restart = function () {
  47317. this._paused = false;
  47318. };
  47319. Animatable.prototype.stop = function (animationName) {
  47320. if (animationName) {
  47321. var idx = this._scene._activeAnimatables.indexOf(this);
  47322. if (idx > -1) {
  47323. var runtimeAnimations = this._runtimeAnimations;
  47324. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47325. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47326. continue;
  47327. }
  47328. runtimeAnimations[index].dispose();
  47329. runtimeAnimations.splice(index, 1);
  47330. }
  47331. if (runtimeAnimations.length == 0) {
  47332. this._scene._activeAnimatables.splice(idx, 1);
  47333. if (this.onAnimationEnd) {
  47334. this.onAnimationEnd();
  47335. }
  47336. }
  47337. }
  47338. }
  47339. else {
  47340. var index = this._scene._activeAnimatables.indexOf(this);
  47341. if (index > -1) {
  47342. this._scene._activeAnimatables.splice(index, 1);
  47343. var runtimeAnimations = this._runtimeAnimations;
  47344. for (var index = 0; index < runtimeAnimations.length; index++) {
  47345. runtimeAnimations[index].dispose();
  47346. }
  47347. if (this.onAnimationEnd) {
  47348. this.onAnimationEnd();
  47349. }
  47350. }
  47351. }
  47352. };
  47353. Animatable.prototype._animate = function (delay) {
  47354. if (this._paused) {
  47355. this.animationStarted = false;
  47356. if (this._pausedDelay === null) {
  47357. this._pausedDelay = delay;
  47358. }
  47359. return true;
  47360. }
  47361. if (this._localDelayOffset === null) {
  47362. this._localDelayOffset = delay;
  47363. this._pausedDelay = null;
  47364. }
  47365. else if (this._pausedDelay !== null) {
  47366. this._localDelayOffset += delay - this._pausedDelay;
  47367. this._pausedDelay = null;
  47368. }
  47369. // Animating
  47370. var running = false;
  47371. var runtimeAnimations = this._runtimeAnimations;
  47372. var index;
  47373. for (index = 0; index < runtimeAnimations.length; index++) {
  47374. var animation = runtimeAnimations[index];
  47375. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47376. running = running || isRunning;
  47377. }
  47378. this.animationStarted = running;
  47379. if (!running) {
  47380. // Remove from active animatables
  47381. index = this._scene._activeAnimatables.indexOf(this);
  47382. this._scene._activeAnimatables.splice(index, 1);
  47383. // Dispose all runtime animations
  47384. for (index = 0; index < runtimeAnimations.length; index++) {
  47385. runtimeAnimations[index].dispose();
  47386. }
  47387. }
  47388. if (!running && this.onAnimationEnd) {
  47389. this.onAnimationEnd();
  47390. this.onAnimationEnd = null;
  47391. }
  47392. return running;
  47393. };
  47394. return Animatable;
  47395. }());
  47396. BABYLON.Animatable = Animatable;
  47397. })(BABYLON || (BABYLON = {}));
  47398. //# sourceMappingURL=babylon.animatable.js.map
  47399. var BABYLON;
  47400. (function (BABYLON) {
  47401. var EasingFunction = /** @class */ (function () {
  47402. function EasingFunction() {
  47403. // Properties
  47404. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47405. }
  47406. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47407. get: function () {
  47408. return EasingFunction._EASINGMODE_EASEIN;
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47414. get: function () {
  47415. return EasingFunction._EASINGMODE_EASEOUT;
  47416. },
  47417. enumerable: true,
  47418. configurable: true
  47419. });
  47420. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47421. get: function () {
  47422. return EasingFunction._EASINGMODE_EASEINOUT;
  47423. },
  47424. enumerable: true,
  47425. configurable: true
  47426. });
  47427. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47428. var n = Math.min(Math.max(easingMode, 0), 2);
  47429. this._easingMode = n;
  47430. };
  47431. EasingFunction.prototype.getEasingMode = function () {
  47432. return this._easingMode;
  47433. };
  47434. EasingFunction.prototype.easeInCore = function (gradient) {
  47435. throw new Error('You must implement this method');
  47436. };
  47437. EasingFunction.prototype.ease = function (gradient) {
  47438. switch (this._easingMode) {
  47439. case EasingFunction.EASINGMODE_EASEIN:
  47440. return this.easeInCore(gradient);
  47441. case EasingFunction.EASINGMODE_EASEOUT:
  47442. return (1 - this.easeInCore(1 - gradient));
  47443. }
  47444. if (gradient >= 0.5) {
  47445. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47446. }
  47447. return (this.easeInCore(gradient * 2) * 0.5);
  47448. };
  47449. //Statics
  47450. EasingFunction._EASINGMODE_EASEIN = 0;
  47451. EasingFunction._EASINGMODE_EASEOUT = 1;
  47452. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47453. return EasingFunction;
  47454. }());
  47455. BABYLON.EasingFunction = EasingFunction;
  47456. var CircleEase = /** @class */ (function (_super) {
  47457. __extends(CircleEase, _super);
  47458. function CircleEase() {
  47459. return _super !== null && _super.apply(this, arguments) || this;
  47460. }
  47461. CircleEase.prototype.easeInCore = function (gradient) {
  47462. gradient = Math.max(0, Math.min(1, gradient));
  47463. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47464. };
  47465. return CircleEase;
  47466. }(EasingFunction));
  47467. BABYLON.CircleEase = CircleEase;
  47468. var BackEase = /** @class */ (function (_super) {
  47469. __extends(BackEase, _super);
  47470. function BackEase(amplitude) {
  47471. if (amplitude === void 0) { amplitude = 1; }
  47472. var _this = _super.call(this) || this;
  47473. _this.amplitude = amplitude;
  47474. return _this;
  47475. }
  47476. BackEase.prototype.easeInCore = function (gradient) {
  47477. var num = Math.max(0, this.amplitude);
  47478. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47479. };
  47480. return BackEase;
  47481. }(EasingFunction));
  47482. BABYLON.BackEase = BackEase;
  47483. var BounceEase = /** @class */ (function (_super) {
  47484. __extends(BounceEase, _super);
  47485. function BounceEase(bounces, bounciness) {
  47486. if (bounces === void 0) { bounces = 3; }
  47487. if (bounciness === void 0) { bounciness = 2; }
  47488. var _this = _super.call(this) || this;
  47489. _this.bounces = bounces;
  47490. _this.bounciness = bounciness;
  47491. return _this;
  47492. }
  47493. BounceEase.prototype.easeInCore = function (gradient) {
  47494. var y = Math.max(0.0, this.bounces);
  47495. var bounciness = this.bounciness;
  47496. if (bounciness <= 1.0) {
  47497. bounciness = 1.001;
  47498. }
  47499. var num9 = Math.pow(bounciness, y);
  47500. var num5 = 1.0 - bounciness;
  47501. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47502. var num15 = gradient * num4;
  47503. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47504. var num3 = Math.floor(num65);
  47505. var num13 = num3 + 1.0;
  47506. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47507. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47508. var num7 = (num8 + num12) * 0.5;
  47509. var num6 = gradient - num7;
  47510. var num2 = num7 - num8;
  47511. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47512. };
  47513. return BounceEase;
  47514. }(EasingFunction));
  47515. BABYLON.BounceEase = BounceEase;
  47516. var CubicEase = /** @class */ (function (_super) {
  47517. __extends(CubicEase, _super);
  47518. function CubicEase() {
  47519. return _super !== null && _super.apply(this, arguments) || this;
  47520. }
  47521. CubicEase.prototype.easeInCore = function (gradient) {
  47522. return (gradient * gradient * gradient);
  47523. };
  47524. return CubicEase;
  47525. }(EasingFunction));
  47526. BABYLON.CubicEase = CubicEase;
  47527. var ElasticEase = /** @class */ (function (_super) {
  47528. __extends(ElasticEase, _super);
  47529. function ElasticEase(oscillations, springiness) {
  47530. if (oscillations === void 0) { oscillations = 3; }
  47531. if (springiness === void 0) { springiness = 3; }
  47532. var _this = _super.call(this) || this;
  47533. _this.oscillations = oscillations;
  47534. _this.springiness = springiness;
  47535. return _this;
  47536. }
  47537. ElasticEase.prototype.easeInCore = function (gradient) {
  47538. var num2;
  47539. var num3 = Math.max(0.0, this.oscillations);
  47540. var num = Math.max(0.0, this.springiness);
  47541. if (num == 0) {
  47542. num2 = gradient;
  47543. }
  47544. else {
  47545. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47546. }
  47547. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47548. };
  47549. return ElasticEase;
  47550. }(EasingFunction));
  47551. BABYLON.ElasticEase = ElasticEase;
  47552. var ExponentialEase = /** @class */ (function (_super) {
  47553. __extends(ExponentialEase, _super);
  47554. function ExponentialEase(exponent) {
  47555. if (exponent === void 0) { exponent = 2; }
  47556. var _this = _super.call(this) || this;
  47557. _this.exponent = exponent;
  47558. return _this;
  47559. }
  47560. ExponentialEase.prototype.easeInCore = function (gradient) {
  47561. if (this.exponent <= 0) {
  47562. return gradient;
  47563. }
  47564. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47565. };
  47566. return ExponentialEase;
  47567. }(EasingFunction));
  47568. BABYLON.ExponentialEase = ExponentialEase;
  47569. var PowerEase = /** @class */ (function (_super) {
  47570. __extends(PowerEase, _super);
  47571. function PowerEase(power) {
  47572. if (power === void 0) { power = 2; }
  47573. var _this = _super.call(this) || this;
  47574. _this.power = power;
  47575. return _this;
  47576. }
  47577. PowerEase.prototype.easeInCore = function (gradient) {
  47578. var y = Math.max(0.0, this.power);
  47579. return Math.pow(gradient, y);
  47580. };
  47581. return PowerEase;
  47582. }(EasingFunction));
  47583. BABYLON.PowerEase = PowerEase;
  47584. var QuadraticEase = /** @class */ (function (_super) {
  47585. __extends(QuadraticEase, _super);
  47586. function QuadraticEase() {
  47587. return _super !== null && _super.apply(this, arguments) || this;
  47588. }
  47589. QuadraticEase.prototype.easeInCore = function (gradient) {
  47590. return (gradient * gradient);
  47591. };
  47592. return QuadraticEase;
  47593. }(EasingFunction));
  47594. BABYLON.QuadraticEase = QuadraticEase;
  47595. var QuarticEase = /** @class */ (function (_super) {
  47596. __extends(QuarticEase, _super);
  47597. function QuarticEase() {
  47598. return _super !== null && _super.apply(this, arguments) || this;
  47599. }
  47600. QuarticEase.prototype.easeInCore = function (gradient) {
  47601. return (gradient * gradient * gradient * gradient);
  47602. };
  47603. return QuarticEase;
  47604. }(EasingFunction));
  47605. BABYLON.QuarticEase = QuarticEase;
  47606. var QuinticEase = /** @class */ (function (_super) {
  47607. __extends(QuinticEase, _super);
  47608. function QuinticEase() {
  47609. return _super !== null && _super.apply(this, arguments) || this;
  47610. }
  47611. QuinticEase.prototype.easeInCore = function (gradient) {
  47612. return (gradient * gradient * gradient * gradient * gradient);
  47613. };
  47614. return QuinticEase;
  47615. }(EasingFunction));
  47616. BABYLON.QuinticEase = QuinticEase;
  47617. var SineEase = /** @class */ (function (_super) {
  47618. __extends(SineEase, _super);
  47619. function SineEase() {
  47620. return _super !== null && _super.apply(this, arguments) || this;
  47621. }
  47622. SineEase.prototype.easeInCore = function (gradient) {
  47623. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47624. };
  47625. return SineEase;
  47626. }(EasingFunction));
  47627. BABYLON.SineEase = SineEase;
  47628. var BezierCurveEase = /** @class */ (function (_super) {
  47629. __extends(BezierCurveEase, _super);
  47630. function BezierCurveEase(x1, y1, x2, y2) {
  47631. if (x1 === void 0) { x1 = 0; }
  47632. if (y1 === void 0) { y1 = 0; }
  47633. if (x2 === void 0) { x2 = 1; }
  47634. if (y2 === void 0) { y2 = 1; }
  47635. var _this = _super.call(this) || this;
  47636. _this.x1 = x1;
  47637. _this.y1 = y1;
  47638. _this.x2 = x2;
  47639. _this.y2 = y2;
  47640. return _this;
  47641. }
  47642. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47643. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47644. };
  47645. return BezierCurveEase;
  47646. }(EasingFunction));
  47647. BABYLON.BezierCurveEase = BezierCurveEase;
  47648. })(BABYLON || (BABYLON = {}));
  47649. //# sourceMappingURL=babylon.easing.js.map
  47650. var BABYLON;
  47651. (function (BABYLON) {
  47652. var Condition = /** @class */ (function () {
  47653. function Condition(actionManager) {
  47654. this._actionManager = actionManager;
  47655. }
  47656. Condition.prototype.isValid = function () {
  47657. return true;
  47658. };
  47659. Condition.prototype._getProperty = function (propertyPath) {
  47660. return this._actionManager._getProperty(propertyPath);
  47661. };
  47662. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47663. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47664. };
  47665. Condition.prototype.serialize = function () {
  47666. };
  47667. Condition.prototype._serialize = function (serializedCondition) {
  47668. return {
  47669. type: 2,
  47670. children: [],
  47671. name: serializedCondition.name,
  47672. properties: serializedCondition.properties
  47673. };
  47674. };
  47675. return Condition;
  47676. }());
  47677. BABYLON.Condition = Condition;
  47678. var ValueCondition = /** @class */ (function (_super) {
  47679. __extends(ValueCondition, _super);
  47680. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47681. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47682. var _this = _super.call(this, actionManager) || this;
  47683. _this.propertyPath = propertyPath;
  47684. _this.value = value;
  47685. _this.operator = operator;
  47686. _this._target = target;
  47687. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47688. _this._property = _this._getProperty(_this.propertyPath);
  47689. return _this;
  47690. }
  47691. Object.defineProperty(ValueCondition, "IsEqual", {
  47692. get: function () {
  47693. return ValueCondition._IsEqual;
  47694. },
  47695. enumerable: true,
  47696. configurable: true
  47697. });
  47698. Object.defineProperty(ValueCondition, "IsDifferent", {
  47699. get: function () {
  47700. return ValueCondition._IsDifferent;
  47701. },
  47702. enumerable: true,
  47703. configurable: true
  47704. });
  47705. Object.defineProperty(ValueCondition, "IsGreater", {
  47706. get: function () {
  47707. return ValueCondition._IsGreater;
  47708. },
  47709. enumerable: true,
  47710. configurable: true
  47711. });
  47712. Object.defineProperty(ValueCondition, "IsLesser", {
  47713. get: function () {
  47714. return ValueCondition._IsLesser;
  47715. },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. // Methods
  47720. ValueCondition.prototype.isValid = function () {
  47721. switch (this.operator) {
  47722. case ValueCondition.IsGreater:
  47723. return this._effectiveTarget[this._property] > this.value;
  47724. case ValueCondition.IsLesser:
  47725. return this._effectiveTarget[this._property] < this.value;
  47726. case ValueCondition.IsEqual:
  47727. case ValueCondition.IsDifferent:
  47728. var check;
  47729. if (this.value.equals) {
  47730. check = this.value.equals(this._effectiveTarget[this._property]);
  47731. }
  47732. else {
  47733. check = this.value === this._effectiveTarget[this._property];
  47734. }
  47735. return this.operator === ValueCondition.IsEqual ? check : !check;
  47736. }
  47737. return false;
  47738. };
  47739. ValueCondition.prototype.serialize = function () {
  47740. return this._serialize({
  47741. name: "ValueCondition",
  47742. properties: [
  47743. BABYLON.Action._GetTargetProperty(this._target),
  47744. { name: "propertyPath", value: this.propertyPath },
  47745. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47746. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47747. ]
  47748. });
  47749. };
  47750. ValueCondition.GetOperatorName = function (operator) {
  47751. switch (operator) {
  47752. case ValueCondition._IsEqual: return "IsEqual";
  47753. case ValueCondition._IsDifferent: return "IsDifferent";
  47754. case ValueCondition._IsGreater: return "IsGreater";
  47755. case ValueCondition._IsLesser: return "IsLesser";
  47756. default: return "";
  47757. }
  47758. };
  47759. // Statics
  47760. ValueCondition._IsEqual = 0;
  47761. ValueCondition._IsDifferent = 1;
  47762. ValueCondition._IsGreater = 2;
  47763. ValueCondition._IsLesser = 3;
  47764. return ValueCondition;
  47765. }(Condition));
  47766. BABYLON.ValueCondition = ValueCondition;
  47767. var PredicateCondition = /** @class */ (function (_super) {
  47768. __extends(PredicateCondition, _super);
  47769. function PredicateCondition(actionManager, predicate) {
  47770. var _this = _super.call(this, actionManager) || this;
  47771. _this.predicate = predicate;
  47772. return _this;
  47773. }
  47774. PredicateCondition.prototype.isValid = function () {
  47775. return this.predicate();
  47776. };
  47777. return PredicateCondition;
  47778. }(Condition));
  47779. BABYLON.PredicateCondition = PredicateCondition;
  47780. var StateCondition = /** @class */ (function (_super) {
  47781. __extends(StateCondition, _super);
  47782. function StateCondition(actionManager, target, value) {
  47783. var _this = _super.call(this, actionManager) || this;
  47784. _this.value = value;
  47785. _this._target = target;
  47786. return _this;
  47787. }
  47788. // Methods
  47789. StateCondition.prototype.isValid = function () {
  47790. return this._target.state === this.value;
  47791. };
  47792. StateCondition.prototype.serialize = function () {
  47793. return this._serialize({
  47794. name: "StateCondition",
  47795. properties: [
  47796. BABYLON.Action._GetTargetProperty(this._target),
  47797. { name: "value", value: this.value }
  47798. ]
  47799. });
  47800. };
  47801. return StateCondition;
  47802. }(Condition));
  47803. BABYLON.StateCondition = StateCondition;
  47804. })(BABYLON || (BABYLON = {}));
  47805. //# sourceMappingURL=babylon.condition.js.map
  47806. var BABYLON;
  47807. (function (BABYLON) {
  47808. var Action = /** @class */ (function () {
  47809. function Action(triggerOptions, condition) {
  47810. this.triggerOptions = triggerOptions;
  47811. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47812. if (triggerOptions.parameter) {
  47813. this.trigger = triggerOptions.trigger;
  47814. this._triggerParameter = triggerOptions.parameter;
  47815. }
  47816. else {
  47817. this.trigger = triggerOptions;
  47818. }
  47819. this._nextActiveAction = this;
  47820. this._condition = condition;
  47821. }
  47822. // Methods
  47823. Action.prototype._prepare = function () {
  47824. };
  47825. Action.prototype.getTriggerParameter = function () {
  47826. return this._triggerParameter;
  47827. };
  47828. Action.prototype._executeCurrent = function (evt) {
  47829. if (this._nextActiveAction._condition) {
  47830. var condition = this._nextActiveAction._condition;
  47831. var currentRenderId = this._actionManager.getScene().getRenderId();
  47832. // We cache the current evaluation for the current frame
  47833. if (condition._evaluationId === currentRenderId) {
  47834. if (!condition._currentResult) {
  47835. return;
  47836. }
  47837. }
  47838. else {
  47839. condition._evaluationId = currentRenderId;
  47840. if (!condition.isValid()) {
  47841. condition._currentResult = false;
  47842. return;
  47843. }
  47844. condition._currentResult = true;
  47845. }
  47846. }
  47847. this.onBeforeExecuteObservable.notifyObservers(this);
  47848. this._nextActiveAction.execute(evt);
  47849. this.skipToNextActiveAction();
  47850. };
  47851. Action.prototype.execute = function (evt) {
  47852. };
  47853. Action.prototype.skipToNextActiveAction = function () {
  47854. if (this._nextActiveAction._child) {
  47855. if (!this._nextActiveAction._child._actionManager) {
  47856. this._nextActiveAction._child._actionManager = this._actionManager;
  47857. }
  47858. this._nextActiveAction = this._nextActiveAction._child;
  47859. }
  47860. else {
  47861. this._nextActiveAction = this;
  47862. }
  47863. };
  47864. Action.prototype.then = function (action) {
  47865. this._child = action;
  47866. action._actionManager = this._actionManager;
  47867. action._prepare();
  47868. return action;
  47869. };
  47870. Action.prototype._getProperty = function (propertyPath) {
  47871. return this._actionManager._getProperty(propertyPath);
  47872. };
  47873. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47874. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47875. };
  47876. Action.prototype.serialize = function (parent) {
  47877. };
  47878. // Called by BABYLON.Action objects in serialize(...). Internal use
  47879. Action.prototype._serialize = function (serializedAction, parent) {
  47880. var serializationObject = {
  47881. type: 1,
  47882. children: [],
  47883. name: serializedAction.name,
  47884. properties: serializedAction.properties || []
  47885. };
  47886. // Serialize child
  47887. if (this._child) {
  47888. this._child.serialize(serializationObject);
  47889. }
  47890. // Check if "this" has a condition
  47891. if (this._condition) {
  47892. var serializedCondition = this._condition.serialize();
  47893. serializedCondition.children.push(serializationObject);
  47894. if (parent) {
  47895. parent.children.push(serializedCondition);
  47896. }
  47897. return serializedCondition;
  47898. }
  47899. if (parent) {
  47900. parent.children.push(serializationObject);
  47901. }
  47902. return serializationObject;
  47903. };
  47904. Action._SerializeValueAsString = function (value) {
  47905. if (typeof value === "number") {
  47906. return value.toString();
  47907. }
  47908. if (typeof value === "boolean") {
  47909. return value ? "true" : "false";
  47910. }
  47911. if (value instanceof BABYLON.Vector2) {
  47912. return value.x + ", " + value.y;
  47913. }
  47914. if (value instanceof BABYLON.Vector3) {
  47915. return value.x + ", " + value.y + ", " + value.z;
  47916. }
  47917. if (value instanceof BABYLON.Color3) {
  47918. return value.r + ", " + value.g + ", " + value.b;
  47919. }
  47920. if (value instanceof BABYLON.Color4) {
  47921. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47922. }
  47923. return value; // string
  47924. };
  47925. Action._GetTargetProperty = function (target) {
  47926. return {
  47927. name: "target",
  47928. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47929. : target instanceof BABYLON.Light ? "LightProperties"
  47930. : target instanceof BABYLON.Camera ? "CameraProperties"
  47931. : "SceneProperties",
  47932. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47933. };
  47934. };
  47935. return Action;
  47936. }());
  47937. BABYLON.Action = Action;
  47938. })(BABYLON || (BABYLON = {}));
  47939. //# sourceMappingURL=babylon.action.js.map
  47940. var BABYLON;
  47941. (function (BABYLON) {
  47942. /**
  47943. * ActionEvent is the event beint sent when an action is triggered.
  47944. */
  47945. var ActionEvent = /** @class */ (function () {
  47946. /**
  47947. * @param source The mesh or sprite that triggered the action.
  47948. * @param pointerX The X mouse cursor position at the time of the event
  47949. * @param pointerY The Y mouse cursor position at the time of the event
  47950. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47951. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47952. */
  47953. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47954. this.source = source;
  47955. this.pointerX = pointerX;
  47956. this.pointerY = pointerY;
  47957. this.meshUnderPointer = meshUnderPointer;
  47958. this.sourceEvent = sourceEvent;
  47959. this.additionalData = additionalData;
  47960. }
  47961. /**
  47962. * Helper function to auto-create an ActionEvent from a source mesh.
  47963. * @param source The source mesh that triggered the event
  47964. * @param evt {Event} The original (browser) event
  47965. */
  47966. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47967. var scene = source.getScene();
  47968. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47969. };
  47970. /**
  47971. * Helper function to auto-create an ActionEvent from a source mesh.
  47972. * @param source The source sprite that triggered the event
  47973. * @param scene Scene associated with the sprite
  47974. * @param evt {Event} The original (browser) event
  47975. */
  47976. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47977. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47978. };
  47979. /**
  47980. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47981. * @param scene the scene where the event occurred
  47982. * @param evt {Event} The original (browser) event
  47983. */
  47984. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47985. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47986. };
  47987. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47988. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47989. };
  47990. return ActionEvent;
  47991. }());
  47992. BABYLON.ActionEvent = ActionEvent;
  47993. /**
  47994. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47995. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47996. */
  47997. var ActionManager = /** @class */ (function () {
  47998. function ActionManager(scene) {
  47999. // Members
  48000. this.actions = new Array();
  48001. this.hoverCursor = '';
  48002. this._scene = scene;
  48003. scene._actionManagers.push(this);
  48004. }
  48005. Object.defineProperty(ActionManager, "NothingTrigger", {
  48006. get: function () {
  48007. return ActionManager._NothingTrigger;
  48008. },
  48009. enumerable: true,
  48010. configurable: true
  48011. });
  48012. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48013. get: function () {
  48014. return ActionManager._OnPickTrigger;
  48015. },
  48016. enumerable: true,
  48017. configurable: true
  48018. });
  48019. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48020. get: function () {
  48021. return ActionManager._OnLeftPickTrigger;
  48022. },
  48023. enumerable: true,
  48024. configurable: true
  48025. });
  48026. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48027. get: function () {
  48028. return ActionManager._OnRightPickTrigger;
  48029. },
  48030. enumerable: true,
  48031. configurable: true
  48032. });
  48033. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48034. get: function () {
  48035. return ActionManager._OnCenterPickTrigger;
  48036. },
  48037. enumerable: true,
  48038. configurable: true
  48039. });
  48040. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48041. get: function () {
  48042. return ActionManager._OnPickDownTrigger;
  48043. },
  48044. enumerable: true,
  48045. configurable: true
  48046. });
  48047. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48048. get: function () {
  48049. return ActionManager._OnDoublePickTrigger;
  48050. },
  48051. enumerable: true,
  48052. configurable: true
  48053. });
  48054. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48055. get: function () {
  48056. return ActionManager._OnPickUpTrigger;
  48057. },
  48058. enumerable: true,
  48059. configurable: true
  48060. });
  48061. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48062. /// This trigger will only be raised if you also declared a OnPickDown
  48063. get: function () {
  48064. return ActionManager._OnPickOutTrigger;
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48070. get: function () {
  48071. return ActionManager._OnLongPressTrigger;
  48072. },
  48073. enumerable: true,
  48074. configurable: true
  48075. });
  48076. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48077. get: function () {
  48078. return ActionManager._OnPointerOverTrigger;
  48079. },
  48080. enumerable: true,
  48081. configurable: true
  48082. });
  48083. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48084. get: function () {
  48085. return ActionManager._OnPointerOutTrigger;
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48091. get: function () {
  48092. return ActionManager._OnEveryFrameTrigger;
  48093. },
  48094. enumerable: true,
  48095. configurable: true
  48096. });
  48097. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48098. get: function () {
  48099. return ActionManager._OnIntersectionEnterTrigger;
  48100. },
  48101. enumerable: true,
  48102. configurable: true
  48103. });
  48104. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48105. get: function () {
  48106. return ActionManager._OnIntersectionExitTrigger;
  48107. },
  48108. enumerable: true,
  48109. configurable: true
  48110. });
  48111. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48112. get: function () {
  48113. return ActionManager._OnKeyDownTrigger;
  48114. },
  48115. enumerable: true,
  48116. configurable: true
  48117. });
  48118. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48119. get: function () {
  48120. return ActionManager._OnKeyUpTrigger;
  48121. },
  48122. enumerable: true,
  48123. configurable: true
  48124. });
  48125. // Methods
  48126. ActionManager.prototype.dispose = function () {
  48127. var index = this._scene._actionManagers.indexOf(this);
  48128. for (var i = 0; i < this.actions.length; i++) {
  48129. var action = this.actions[i];
  48130. ActionManager.Triggers[action.trigger]--;
  48131. if (ActionManager.Triggers[action.trigger] === 0) {
  48132. delete ActionManager.Triggers[action.trigger];
  48133. }
  48134. }
  48135. if (index > -1) {
  48136. this._scene._actionManagers.splice(index, 1);
  48137. }
  48138. };
  48139. ActionManager.prototype.getScene = function () {
  48140. return this._scene;
  48141. };
  48142. /**
  48143. * Does this action manager handles actions of any of the given triggers
  48144. * @param {number[]} triggers - the triggers to be tested
  48145. * @return {boolean} whether one (or more) of the triggers is handeled
  48146. */
  48147. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48148. for (var index = 0; index < this.actions.length; index++) {
  48149. var action = this.actions[index];
  48150. if (triggers.indexOf(action.trigger) > -1) {
  48151. return true;
  48152. }
  48153. }
  48154. return false;
  48155. };
  48156. /**
  48157. * Does this action manager handles actions of a given trigger
  48158. * @param {number} trigger - the trigger to be tested
  48159. * @return {boolean} whether the trigger is handeled
  48160. */
  48161. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48162. for (var index = 0; index < this.actions.length; index++) {
  48163. var action = this.actions[index];
  48164. if (action.trigger === trigger) {
  48165. return true;
  48166. }
  48167. }
  48168. return false;
  48169. };
  48170. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48171. /**
  48172. * Does this action manager has pointer triggers
  48173. * @return {boolean} whether or not it has pointer triggers
  48174. */
  48175. get: function () {
  48176. for (var index = 0; index < this.actions.length; index++) {
  48177. var action = this.actions[index];
  48178. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48179. return true;
  48180. }
  48181. }
  48182. return false;
  48183. },
  48184. enumerable: true,
  48185. configurable: true
  48186. });
  48187. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48188. /**
  48189. * Does this action manager has pick triggers
  48190. * @return {boolean} whether or not it has pick triggers
  48191. */
  48192. get: function () {
  48193. for (var index = 0; index < this.actions.length; index++) {
  48194. var action = this.actions[index];
  48195. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48196. return true;
  48197. }
  48198. }
  48199. return false;
  48200. },
  48201. enumerable: true,
  48202. configurable: true
  48203. });
  48204. Object.defineProperty(ActionManager, "HasTriggers", {
  48205. /**
  48206. * Does exist one action manager with at least one trigger
  48207. * @return {boolean} whether or not it exists one action manager with one trigger
  48208. **/
  48209. get: function () {
  48210. for (var t in ActionManager.Triggers) {
  48211. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48212. return true;
  48213. }
  48214. }
  48215. return false;
  48216. },
  48217. enumerable: true,
  48218. configurable: true
  48219. });
  48220. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48221. /**
  48222. * Does exist one action manager with at least one pick trigger
  48223. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48224. **/
  48225. get: function () {
  48226. for (var t in ActionManager.Triggers) {
  48227. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48228. var t_int = parseInt(t);
  48229. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48230. return true;
  48231. }
  48232. }
  48233. }
  48234. return false;
  48235. },
  48236. enumerable: true,
  48237. configurable: true
  48238. });
  48239. /**
  48240. * Does exist one action manager that handles actions of a given trigger
  48241. * @param {number} trigger - the trigger to be tested
  48242. * @return {boolean} whether the trigger is handeled by at least one action manager
  48243. **/
  48244. ActionManager.HasSpecificTrigger = function (trigger) {
  48245. for (var t in ActionManager.Triggers) {
  48246. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48247. var t_int = parseInt(t);
  48248. if (t_int === trigger) {
  48249. return true;
  48250. }
  48251. }
  48252. }
  48253. return false;
  48254. };
  48255. /**
  48256. * Registers an action to this action manager
  48257. * @param {BABYLON.Action} action - the action to be registered
  48258. * @return {BABYLON.Action} the action amended (prepared) after registration
  48259. */
  48260. ActionManager.prototype.registerAction = function (action) {
  48261. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48262. if (this.getScene().actionManager !== this) {
  48263. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48264. return null;
  48265. }
  48266. }
  48267. this.actions.push(action);
  48268. if (ActionManager.Triggers[action.trigger]) {
  48269. ActionManager.Triggers[action.trigger]++;
  48270. }
  48271. else {
  48272. ActionManager.Triggers[action.trigger] = 1;
  48273. }
  48274. action._actionManager = this;
  48275. action._prepare();
  48276. return action;
  48277. };
  48278. /**
  48279. * Unregisters an action to this action manager
  48280. * @param action The action to be unregistered
  48281. * @return whether the action has been unregistered
  48282. */
  48283. ActionManager.prototype.unregisterAction = function (action) {
  48284. var index = this.actions.indexOf(action);
  48285. if (index !== -1) {
  48286. this.actions.splice(index, 1);
  48287. ActionManager.Triggers[action.trigger] -= 1;
  48288. if (ActionManager.Triggers[action.trigger] === 0) {
  48289. delete ActionManager.Triggers[action.trigger];
  48290. }
  48291. delete action._actionManager;
  48292. return true;
  48293. }
  48294. return false;
  48295. };
  48296. /**
  48297. * Process a specific trigger
  48298. * @param {number} trigger - the trigger to process
  48299. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48300. */
  48301. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48302. for (var index = 0; index < this.actions.length; index++) {
  48303. var action = this.actions[index];
  48304. if (action.trigger === trigger) {
  48305. if (evt) {
  48306. if (trigger === ActionManager.OnKeyUpTrigger
  48307. || trigger === ActionManager.OnKeyDownTrigger) {
  48308. var parameter = action.getTriggerParameter();
  48309. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48310. if (!parameter.toLowerCase) {
  48311. continue;
  48312. }
  48313. var lowerCase = parameter.toLowerCase();
  48314. if (lowerCase !== evt.sourceEvent.key) {
  48315. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48316. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48317. if (actualkey !== lowerCase) {
  48318. continue;
  48319. }
  48320. }
  48321. }
  48322. }
  48323. }
  48324. action._executeCurrent(evt);
  48325. }
  48326. }
  48327. };
  48328. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48329. var properties = propertyPath.split(".");
  48330. for (var index = 0; index < properties.length - 1; index++) {
  48331. target = target[properties[index]];
  48332. }
  48333. return target;
  48334. };
  48335. ActionManager.prototype._getProperty = function (propertyPath) {
  48336. var properties = propertyPath.split(".");
  48337. return properties[properties.length - 1];
  48338. };
  48339. ActionManager.prototype.serialize = function (name) {
  48340. var root = {
  48341. children: new Array(),
  48342. name: name,
  48343. type: 3,
  48344. properties: new Array() // Empty for root but required
  48345. };
  48346. for (var i = 0; i < this.actions.length; i++) {
  48347. var triggerObject = {
  48348. type: 0,
  48349. children: new Array(),
  48350. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48351. properties: new Array()
  48352. };
  48353. var triggerOptions = this.actions[i].triggerOptions;
  48354. if (triggerOptions && typeof triggerOptions !== "number") {
  48355. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48356. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48357. }
  48358. else {
  48359. var parameter = {};
  48360. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48361. if (triggerOptions.parameter.mesh) {
  48362. parameter._meshId = triggerOptions.parameter.mesh.id;
  48363. }
  48364. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48365. }
  48366. }
  48367. // Serialize child action, recursively
  48368. this.actions[i].serialize(triggerObject);
  48369. // Add serialized trigger
  48370. root.children.push(triggerObject);
  48371. }
  48372. return root;
  48373. };
  48374. ActionManager.Parse = function (parsedActions, object, scene) {
  48375. var actionManager = new ActionManager(scene);
  48376. if (object === null)
  48377. scene.actionManager = actionManager;
  48378. else
  48379. object.actionManager = actionManager;
  48380. // instanciate a new object
  48381. var instanciate = function (name, params) {
  48382. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48383. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48384. newInstance.constructor.apply(newInstance, params);
  48385. return newInstance;
  48386. };
  48387. var parseParameter = function (name, value, target, propertyPath) {
  48388. if (propertyPath === null) {
  48389. // String, boolean or float
  48390. var floatValue = parseFloat(value);
  48391. if (value === "true" || value === "false")
  48392. return value === "true";
  48393. else
  48394. return isNaN(floatValue) ? value : floatValue;
  48395. }
  48396. var effectiveTarget = propertyPath.split(".");
  48397. var values = value.split(",");
  48398. // Get effective Target
  48399. for (var i = 0; i < effectiveTarget.length; i++) {
  48400. target = target[effectiveTarget[i]];
  48401. }
  48402. // Return appropriate value with its type
  48403. if (typeof (target) === "boolean")
  48404. return values[0] === "true";
  48405. if (typeof (target) === "string")
  48406. return values[0];
  48407. // Parameters with multiple values such as Vector3 etc.
  48408. var split = new Array();
  48409. for (var i = 0; i < values.length; i++)
  48410. split.push(parseFloat(values[i]));
  48411. if (target instanceof BABYLON.Vector3)
  48412. return BABYLON.Vector3.FromArray(split);
  48413. if (target instanceof BABYLON.Vector4)
  48414. return BABYLON.Vector4.FromArray(split);
  48415. if (target instanceof BABYLON.Color3)
  48416. return BABYLON.Color3.FromArray(split);
  48417. if (target instanceof BABYLON.Color4)
  48418. return BABYLON.Color4.FromArray(split);
  48419. return parseFloat(values[0]);
  48420. };
  48421. // traverse graph per trigger
  48422. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48423. if (combineArray === void 0) { combineArray = null; }
  48424. if (parsedAction.detached)
  48425. return;
  48426. var parameters = new Array();
  48427. var target = null;
  48428. var propertyPath = null;
  48429. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48430. // Parameters
  48431. if (parsedAction.type === 2)
  48432. parameters.push(actionManager);
  48433. else
  48434. parameters.push(trigger);
  48435. if (combine) {
  48436. var actions = new Array();
  48437. for (var j = 0; j < parsedAction.combine.length; j++) {
  48438. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48439. }
  48440. parameters.push(actions);
  48441. }
  48442. else {
  48443. for (var i = 0; i < parsedAction.properties.length; i++) {
  48444. var value = parsedAction.properties[i].value;
  48445. var name = parsedAction.properties[i].name;
  48446. var targetType = parsedAction.properties[i].targetType;
  48447. if (name === "target")
  48448. if (targetType !== null && targetType === "SceneProperties")
  48449. value = target = scene;
  48450. else
  48451. value = target = scene.getNodeByName(value);
  48452. else if (name === "parent")
  48453. value = scene.getNodeByName(value);
  48454. else if (name === "sound")
  48455. value = scene.getSoundByName(value);
  48456. else if (name !== "propertyPath") {
  48457. if (parsedAction.type === 2 && name === "operator")
  48458. value = BABYLON.ValueCondition[value];
  48459. else
  48460. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48461. }
  48462. else {
  48463. propertyPath = value;
  48464. }
  48465. parameters.push(value);
  48466. }
  48467. }
  48468. if (combineArray === null) {
  48469. parameters.push(condition);
  48470. }
  48471. else {
  48472. parameters.push(null);
  48473. }
  48474. // If interpolate value action
  48475. if (parsedAction.name === "InterpolateValueAction") {
  48476. var param = parameters[parameters.length - 2];
  48477. parameters[parameters.length - 1] = param;
  48478. parameters[parameters.length - 2] = condition;
  48479. }
  48480. // Action or condition(s) and not CombineAction
  48481. var newAction = instanciate(parsedAction.name, parameters);
  48482. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48483. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48484. if (action)
  48485. action.then(nothing);
  48486. else
  48487. actionManager.registerAction(nothing);
  48488. action = nothing;
  48489. }
  48490. if (combineArray === null) {
  48491. if (newAction instanceof BABYLON.Condition) {
  48492. condition = newAction;
  48493. newAction = action;
  48494. }
  48495. else {
  48496. condition = null;
  48497. if (action)
  48498. action.then(newAction);
  48499. else
  48500. actionManager.registerAction(newAction);
  48501. }
  48502. }
  48503. else {
  48504. combineArray.push(newAction);
  48505. }
  48506. for (var i = 0; i < parsedAction.children.length; i++)
  48507. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48508. };
  48509. // triggers
  48510. for (var i = 0; i < parsedActions.children.length; i++) {
  48511. var triggerParams;
  48512. var trigger = parsedActions.children[i];
  48513. if (trigger.properties.length > 0) {
  48514. var param = trigger.properties[0].value;
  48515. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48516. if (value._meshId) {
  48517. value.mesh = scene.getMeshByID(value._meshId);
  48518. }
  48519. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48520. }
  48521. else
  48522. triggerParams = ActionManager[trigger.name];
  48523. for (var j = 0; j < trigger.children.length; j++) {
  48524. if (!trigger.detached)
  48525. traverse(trigger.children[j], triggerParams, null, null);
  48526. }
  48527. }
  48528. };
  48529. ActionManager.GetTriggerName = function (trigger) {
  48530. switch (trigger) {
  48531. case 0: return "NothingTrigger";
  48532. case 1: return "OnPickTrigger";
  48533. case 2: return "OnLeftPickTrigger";
  48534. case 3: return "OnRightPickTrigger";
  48535. case 4: return "OnCenterPickTrigger";
  48536. case 5: return "OnPickDownTrigger";
  48537. case 6: return "OnPickUpTrigger";
  48538. case 7: return "OnLongPressTrigger";
  48539. case 8: return "OnPointerOverTrigger";
  48540. case 9: return "OnPointerOutTrigger";
  48541. case 10: return "OnEveryFrameTrigger";
  48542. case 11: return "OnIntersectionEnterTrigger";
  48543. case 12: return "OnIntersectionExitTrigger";
  48544. case 13: return "OnKeyDownTrigger";
  48545. case 14: return "OnKeyUpTrigger";
  48546. case 15: return "OnPickOutTrigger";
  48547. default: return "";
  48548. }
  48549. };
  48550. // Statics
  48551. ActionManager._NothingTrigger = 0;
  48552. ActionManager._OnPickTrigger = 1;
  48553. ActionManager._OnLeftPickTrigger = 2;
  48554. ActionManager._OnRightPickTrigger = 3;
  48555. ActionManager._OnCenterPickTrigger = 4;
  48556. ActionManager._OnPickDownTrigger = 5;
  48557. ActionManager._OnDoublePickTrigger = 6;
  48558. ActionManager._OnPickUpTrigger = 7;
  48559. ActionManager._OnLongPressTrigger = 8;
  48560. ActionManager._OnPointerOverTrigger = 9;
  48561. ActionManager._OnPointerOutTrigger = 10;
  48562. ActionManager._OnEveryFrameTrigger = 11;
  48563. ActionManager._OnIntersectionEnterTrigger = 12;
  48564. ActionManager._OnIntersectionExitTrigger = 13;
  48565. ActionManager._OnKeyDownTrigger = 14;
  48566. ActionManager._OnKeyUpTrigger = 15;
  48567. ActionManager._OnPickOutTrigger = 16;
  48568. ActionManager.Triggers = {};
  48569. return ActionManager;
  48570. }());
  48571. BABYLON.ActionManager = ActionManager;
  48572. })(BABYLON || (BABYLON = {}));
  48573. //# sourceMappingURL=babylon.actionManager.js.map
  48574. var BABYLON;
  48575. (function (BABYLON) {
  48576. var InterpolateValueAction = /** @class */ (function (_super) {
  48577. __extends(InterpolateValueAction, _super);
  48578. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48579. if (duration === void 0) { duration = 1000; }
  48580. var _this = _super.call(this, triggerOptions, condition) || this;
  48581. _this.propertyPath = propertyPath;
  48582. _this.value = value;
  48583. _this.duration = duration;
  48584. _this.stopOtherAnimations = stopOtherAnimations;
  48585. _this.onInterpolationDone = onInterpolationDone;
  48586. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48587. _this._target = _this._effectiveTarget = target;
  48588. return _this;
  48589. }
  48590. InterpolateValueAction.prototype._prepare = function () {
  48591. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48592. this._property = this._getProperty(this.propertyPath);
  48593. };
  48594. InterpolateValueAction.prototype.execute = function () {
  48595. var _this = this;
  48596. var scene = this._actionManager.getScene();
  48597. var keys = [
  48598. {
  48599. frame: 0,
  48600. value: this._effectiveTarget[this._property]
  48601. }, {
  48602. frame: 100,
  48603. value: this.value
  48604. }
  48605. ];
  48606. var dataType;
  48607. if (typeof this.value === "number") {
  48608. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48609. }
  48610. else if (this.value instanceof BABYLON.Color3) {
  48611. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48612. }
  48613. else if (this.value instanceof BABYLON.Vector3) {
  48614. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48615. }
  48616. else if (this.value instanceof BABYLON.Matrix) {
  48617. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48618. }
  48619. else if (this.value instanceof BABYLON.Quaternion) {
  48620. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48621. }
  48622. else {
  48623. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48624. return;
  48625. }
  48626. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48627. animation.setKeys(keys);
  48628. if (this.stopOtherAnimations) {
  48629. scene.stopAnimation(this._effectiveTarget);
  48630. }
  48631. var wrapper = function () {
  48632. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48633. if (_this.onInterpolationDone) {
  48634. _this.onInterpolationDone();
  48635. }
  48636. };
  48637. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48638. };
  48639. InterpolateValueAction.prototype.serialize = function (parent) {
  48640. return _super.prototype._serialize.call(this, {
  48641. name: "InterpolateValueAction",
  48642. properties: [
  48643. BABYLON.Action._GetTargetProperty(this._target),
  48644. { name: "propertyPath", value: this.propertyPath },
  48645. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48646. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48647. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48648. ]
  48649. }, parent);
  48650. };
  48651. return InterpolateValueAction;
  48652. }(BABYLON.Action));
  48653. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48654. })(BABYLON || (BABYLON = {}));
  48655. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48656. var BABYLON;
  48657. (function (BABYLON) {
  48658. var SwitchBooleanAction = /** @class */ (function (_super) {
  48659. __extends(SwitchBooleanAction, _super);
  48660. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48661. var _this = _super.call(this, triggerOptions, condition) || this;
  48662. _this.propertyPath = propertyPath;
  48663. _this._target = _this._effectiveTarget = target;
  48664. return _this;
  48665. }
  48666. SwitchBooleanAction.prototype._prepare = function () {
  48667. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48668. this._property = this._getProperty(this.propertyPath);
  48669. };
  48670. SwitchBooleanAction.prototype.execute = function () {
  48671. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48672. };
  48673. SwitchBooleanAction.prototype.serialize = function (parent) {
  48674. return _super.prototype._serialize.call(this, {
  48675. name: "SwitchBooleanAction",
  48676. properties: [
  48677. BABYLON.Action._GetTargetProperty(this._target),
  48678. { name: "propertyPath", value: this.propertyPath }
  48679. ]
  48680. }, parent);
  48681. };
  48682. return SwitchBooleanAction;
  48683. }(BABYLON.Action));
  48684. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48685. var SetStateAction = /** @class */ (function (_super) {
  48686. __extends(SetStateAction, _super);
  48687. function SetStateAction(triggerOptions, target, value, condition) {
  48688. var _this = _super.call(this, triggerOptions, condition) || this;
  48689. _this.value = value;
  48690. _this._target = target;
  48691. return _this;
  48692. }
  48693. SetStateAction.prototype.execute = function () {
  48694. this._target.state = this.value;
  48695. };
  48696. SetStateAction.prototype.serialize = function (parent) {
  48697. return _super.prototype._serialize.call(this, {
  48698. name: "SetStateAction",
  48699. properties: [
  48700. BABYLON.Action._GetTargetProperty(this._target),
  48701. { name: "value", value: this.value }
  48702. ]
  48703. }, parent);
  48704. };
  48705. return SetStateAction;
  48706. }(BABYLON.Action));
  48707. BABYLON.SetStateAction = SetStateAction;
  48708. var SetValueAction = /** @class */ (function (_super) {
  48709. __extends(SetValueAction, _super);
  48710. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48711. var _this = _super.call(this, triggerOptions, condition) || this;
  48712. _this.propertyPath = propertyPath;
  48713. _this.value = value;
  48714. _this._target = _this._effectiveTarget = target;
  48715. return _this;
  48716. }
  48717. SetValueAction.prototype._prepare = function () {
  48718. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48719. this._property = this._getProperty(this.propertyPath);
  48720. };
  48721. SetValueAction.prototype.execute = function () {
  48722. this._effectiveTarget[this._property] = this.value;
  48723. if (this._target.markAsDirty) {
  48724. this._target.markAsDirty(this._property);
  48725. }
  48726. };
  48727. SetValueAction.prototype.serialize = function (parent) {
  48728. return _super.prototype._serialize.call(this, {
  48729. name: "SetValueAction",
  48730. properties: [
  48731. BABYLON.Action._GetTargetProperty(this._target),
  48732. { name: "propertyPath", value: this.propertyPath },
  48733. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48734. ]
  48735. }, parent);
  48736. };
  48737. return SetValueAction;
  48738. }(BABYLON.Action));
  48739. BABYLON.SetValueAction = SetValueAction;
  48740. var IncrementValueAction = /** @class */ (function (_super) {
  48741. __extends(IncrementValueAction, _super);
  48742. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48743. var _this = _super.call(this, triggerOptions, condition) || this;
  48744. _this.propertyPath = propertyPath;
  48745. _this.value = value;
  48746. _this._target = _this._effectiveTarget = target;
  48747. return _this;
  48748. }
  48749. IncrementValueAction.prototype._prepare = function () {
  48750. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48751. this._property = this._getProperty(this.propertyPath);
  48752. if (typeof this._effectiveTarget[this._property] !== "number") {
  48753. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48754. }
  48755. };
  48756. IncrementValueAction.prototype.execute = function () {
  48757. this._effectiveTarget[this._property] += this.value;
  48758. if (this._target.markAsDirty) {
  48759. this._target.markAsDirty(this._property);
  48760. }
  48761. };
  48762. IncrementValueAction.prototype.serialize = function (parent) {
  48763. return _super.prototype._serialize.call(this, {
  48764. name: "IncrementValueAction",
  48765. properties: [
  48766. BABYLON.Action._GetTargetProperty(this._target),
  48767. { name: "propertyPath", value: this.propertyPath },
  48768. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48769. ]
  48770. }, parent);
  48771. };
  48772. return IncrementValueAction;
  48773. }(BABYLON.Action));
  48774. BABYLON.IncrementValueAction = IncrementValueAction;
  48775. var PlayAnimationAction = /** @class */ (function (_super) {
  48776. __extends(PlayAnimationAction, _super);
  48777. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48778. var _this = _super.call(this, triggerOptions, condition) || this;
  48779. _this.from = from;
  48780. _this.to = to;
  48781. _this.loop = loop;
  48782. _this._target = target;
  48783. return _this;
  48784. }
  48785. PlayAnimationAction.prototype._prepare = function () {
  48786. };
  48787. PlayAnimationAction.prototype.execute = function () {
  48788. var scene = this._actionManager.getScene();
  48789. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48790. };
  48791. PlayAnimationAction.prototype.serialize = function (parent) {
  48792. return _super.prototype._serialize.call(this, {
  48793. name: "PlayAnimationAction",
  48794. properties: [
  48795. BABYLON.Action._GetTargetProperty(this._target),
  48796. { name: "from", value: String(this.from) },
  48797. { name: "to", value: String(this.to) },
  48798. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48799. ]
  48800. }, parent);
  48801. };
  48802. return PlayAnimationAction;
  48803. }(BABYLON.Action));
  48804. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48805. var StopAnimationAction = /** @class */ (function (_super) {
  48806. __extends(StopAnimationAction, _super);
  48807. function StopAnimationAction(triggerOptions, target, condition) {
  48808. var _this = _super.call(this, triggerOptions, condition) || this;
  48809. _this._target = target;
  48810. return _this;
  48811. }
  48812. StopAnimationAction.prototype._prepare = function () {
  48813. };
  48814. StopAnimationAction.prototype.execute = function () {
  48815. var scene = this._actionManager.getScene();
  48816. scene.stopAnimation(this._target);
  48817. };
  48818. StopAnimationAction.prototype.serialize = function (parent) {
  48819. return _super.prototype._serialize.call(this, {
  48820. name: "StopAnimationAction",
  48821. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48822. }, parent);
  48823. };
  48824. return StopAnimationAction;
  48825. }(BABYLON.Action));
  48826. BABYLON.StopAnimationAction = StopAnimationAction;
  48827. var DoNothingAction = /** @class */ (function (_super) {
  48828. __extends(DoNothingAction, _super);
  48829. function DoNothingAction(triggerOptions, condition) {
  48830. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48831. return _super.call(this, triggerOptions, condition) || this;
  48832. }
  48833. DoNothingAction.prototype.execute = function () {
  48834. };
  48835. DoNothingAction.prototype.serialize = function (parent) {
  48836. return _super.prototype._serialize.call(this, {
  48837. name: "DoNothingAction",
  48838. properties: []
  48839. }, parent);
  48840. };
  48841. return DoNothingAction;
  48842. }(BABYLON.Action));
  48843. BABYLON.DoNothingAction = DoNothingAction;
  48844. var CombineAction = /** @class */ (function (_super) {
  48845. __extends(CombineAction, _super);
  48846. function CombineAction(triggerOptions, children, condition) {
  48847. var _this = _super.call(this, triggerOptions, condition) || this;
  48848. _this.children = children;
  48849. return _this;
  48850. }
  48851. CombineAction.prototype._prepare = function () {
  48852. for (var index = 0; index < this.children.length; index++) {
  48853. this.children[index]._actionManager = this._actionManager;
  48854. this.children[index]._prepare();
  48855. }
  48856. };
  48857. CombineAction.prototype.execute = function (evt) {
  48858. for (var index = 0; index < this.children.length; index++) {
  48859. this.children[index].execute(evt);
  48860. }
  48861. };
  48862. CombineAction.prototype.serialize = function (parent) {
  48863. var serializationObject = _super.prototype._serialize.call(this, {
  48864. name: "CombineAction",
  48865. properties: [],
  48866. combine: []
  48867. }, parent);
  48868. for (var i = 0; i < this.children.length; i++) {
  48869. serializationObject.combine.push(this.children[i].serialize(null));
  48870. }
  48871. return serializationObject;
  48872. };
  48873. return CombineAction;
  48874. }(BABYLON.Action));
  48875. BABYLON.CombineAction = CombineAction;
  48876. var ExecuteCodeAction = /** @class */ (function (_super) {
  48877. __extends(ExecuteCodeAction, _super);
  48878. function ExecuteCodeAction(triggerOptions, func, condition) {
  48879. var _this = _super.call(this, triggerOptions, condition) || this;
  48880. _this.func = func;
  48881. return _this;
  48882. }
  48883. ExecuteCodeAction.prototype.execute = function (evt) {
  48884. this.func(evt);
  48885. };
  48886. return ExecuteCodeAction;
  48887. }(BABYLON.Action));
  48888. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48889. var SetParentAction = /** @class */ (function (_super) {
  48890. __extends(SetParentAction, _super);
  48891. function SetParentAction(triggerOptions, target, parent, condition) {
  48892. var _this = _super.call(this, triggerOptions, condition) || this;
  48893. _this._target = target;
  48894. _this._parent = parent;
  48895. return _this;
  48896. }
  48897. SetParentAction.prototype._prepare = function () {
  48898. };
  48899. SetParentAction.prototype.execute = function () {
  48900. if (this._target.parent === this._parent) {
  48901. return;
  48902. }
  48903. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48904. invertParentWorldMatrix.invert();
  48905. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48906. this._target.parent = this._parent;
  48907. };
  48908. SetParentAction.prototype.serialize = function (parent) {
  48909. return _super.prototype._serialize.call(this, {
  48910. name: "SetParentAction",
  48911. properties: [
  48912. BABYLON.Action._GetTargetProperty(this._target),
  48913. BABYLON.Action._GetTargetProperty(this._parent),
  48914. ]
  48915. }, parent);
  48916. };
  48917. return SetParentAction;
  48918. }(BABYLON.Action));
  48919. BABYLON.SetParentAction = SetParentAction;
  48920. var PlaySoundAction = /** @class */ (function (_super) {
  48921. __extends(PlaySoundAction, _super);
  48922. function PlaySoundAction(triggerOptions, sound, condition) {
  48923. var _this = _super.call(this, triggerOptions, condition) || this;
  48924. _this._sound = sound;
  48925. return _this;
  48926. }
  48927. PlaySoundAction.prototype._prepare = function () {
  48928. };
  48929. PlaySoundAction.prototype.execute = function () {
  48930. if (this._sound !== undefined)
  48931. this._sound.play();
  48932. };
  48933. PlaySoundAction.prototype.serialize = function (parent) {
  48934. return _super.prototype._serialize.call(this, {
  48935. name: "PlaySoundAction",
  48936. properties: [{ name: "sound", value: this._sound.name }]
  48937. }, parent);
  48938. };
  48939. return PlaySoundAction;
  48940. }(BABYLON.Action));
  48941. BABYLON.PlaySoundAction = PlaySoundAction;
  48942. var StopSoundAction = /** @class */ (function (_super) {
  48943. __extends(StopSoundAction, _super);
  48944. function StopSoundAction(triggerOptions, sound, condition) {
  48945. var _this = _super.call(this, triggerOptions, condition) || this;
  48946. _this._sound = sound;
  48947. return _this;
  48948. }
  48949. StopSoundAction.prototype._prepare = function () {
  48950. };
  48951. StopSoundAction.prototype.execute = function () {
  48952. if (this._sound !== undefined)
  48953. this._sound.stop();
  48954. };
  48955. StopSoundAction.prototype.serialize = function (parent) {
  48956. return _super.prototype._serialize.call(this, {
  48957. name: "StopSoundAction",
  48958. properties: [{ name: "sound", value: this._sound.name }]
  48959. }, parent);
  48960. };
  48961. return StopSoundAction;
  48962. }(BABYLON.Action));
  48963. BABYLON.StopSoundAction = StopSoundAction;
  48964. })(BABYLON || (BABYLON = {}));
  48965. //# sourceMappingURL=babylon.directActions.js.map
  48966. var BABYLON;
  48967. (function (BABYLON) {
  48968. var SpriteManager = /** @class */ (function () {
  48969. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48970. if (epsilon === void 0) { epsilon = 0.01; }
  48971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48972. this.name = name;
  48973. this.sprites = new Array();
  48974. this.renderingGroupId = 0;
  48975. this.layerMask = 0x0FFFFFFF;
  48976. this.fogEnabled = true;
  48977. this.isPickable = false;
  48978. /**
  48979. * An event triggered when the manager is disposed.
  48980. * @type {BABYLON.Observable}
  48981. */
  48982. this.onDisposeObservable = new BABYLON.Observable();
  48983. this._vertexBuffers = {};
  48984. this._capacity = capacity;
  48985. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48986. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48987. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48988. if (cellSize.width && cellSize.height) {
  48989. this.cellWidth = cellSize.width;
  48990. this.cellHeight = cellSize.height;
  48991. }
  48992. else if (cellSize !== undefined) {
  48993. this.cellWidth = cellSize;
  48994. this.cellHeight = cellSize;
  48995. }
  48996. else {
  48997. return;
  48998. }
  48999. this._epsilon = epsilon;
  49000. this._scene = scene;
  49001. this._scene.spriteManagers.push(this);
  49002. var indices = [];
  49003. var index = 0;
  49004. for (var count = 0; count < capacity; count++) {
  49005. indices.push(index);
  49006. indices.push(index + 1);
  49007. indices.push(index + 2);
  49008. indices.push(index);
  49009. indices.push(index + 2);
  49010. indices.push(index + 3);
  49011. index += 4;
  49012. }
  49013. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49014. // VBO
  49015. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49016. this._vertexData = new Float32Array(capacity * 16 * 4);
  49017. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49018. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49019. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49020. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49021. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49022. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49023. this._vertexBuffers["options"] = options;
  49024. this._vertexBuffers["cellInfo"] = cellInfo;
  49025. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49026. // Effects
  49027. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49028. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49029. }
  49030. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49031. set: function (callback) {
  49032. if (this._onDisposeObserver) {
  49033. this.onDisposeObservable.remove(this._onDisposeObserver);
  49034. }
  49035. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49036. },
  49037. enumerable: true,
  49038. configurable: true
  49039. });
  49040. Object.defineProperty(SpriteManager.prototype, "texture", {
  49041. get: function () {
  49042. return this._spriteTexture;
  49043. },
  49044. set: function (value) {
  49045. this._spriteTexture = value;
  49046. },
  49047. enumerable: true,
  49048. configurable: true
  49049. });
  49050. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49051. var arrayOffset = index * 16;
  49052. if (offsetX === 0)
  49053. offsetX = this._epsilon;
  49054. else if (offsetX === 1)
  49055. offsetX = 1 - this._epsilon;
  49056. if (offsetY === 0)
  49057. offsetY = this._epsilon;
  49058. else if (offsetY === 1)
  49059. offsetY = 1 - this._epsilon;
  49060. this._vertexData[arrayOffset] = sprite.position.x;
  49061. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49062. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49063. this._vertexData[arrayOffset + 3] = sprite.angle;
  49064. this._vertexData[arrayOffset + 4] = sprite.width;
  49065. this._vertexData[arrayOffset + 5] = sprite.height;
  49066. this._vertexData[arrayOffset + 6] = offsetX;
  49067. this._vertexData[arrayOffset + 7] = offsetY;
  49068. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49069. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49070. var offset = (sprite.cellIndex / rowSize) >> 0;
  49071. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49072. this._vertexData[arrayOffset + 11] = offset;
  49073. // Color
  49074. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49075. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49076. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49077. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49078. };
  49079. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49080. var count = Math.min(this._capacity, this.sprites.length);
  49081. var min = BABYLON.Vector3.Zero();
  49082. var max = BABYLON.Vector3.Zero();
  49083. var distance = Number.MAX_VALUE;
  49084. var currentSprite = null;
  49085. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49086. var cameraView = camera.getViewMatrix();
  49087. for (var index = 0; index < count; index++) {
  49088. var sprite = this.sprites[index];
  49089. if (!sprite) {
  49090. continue;
  49091. }
  49092. if (predicate) {
  49093. if (!predicate(sprite)) {
  49094. continue;
  49095. }
  49096. }
  49097. else if (!sprite.isPickable) {
  49098. continue;
  49099. }
  49100. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49101. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49102. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49103. if (ray.intersectsBoxMinMax(min, max)) {
  49104. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49105. if (distance > currentDistance) {
  49106. distance = currentDistance;
  49107. currentSprite = sprite;
  49108. if (fastCheck) {
  49109. break;
  49110. }
  49111. }
  49112. }
  49113. }
  49114. if (currentSprite) {
  49115. var result = new BABYLON.PickingInfo();
  49116. result.hit = true;
  49117. result.pickedSprite = currentSprite;
  49118. result.distance = distance;
  49119. return result;
  49120. }
  49121. return null;
  49122. };
  49123. SpriteManager.prototype.render = function () {
  49124. // Check
  49125. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49126. return;
  49127. var engine = this._scene.getEngine();
  49128. var baseSize = this._spriteTexture.getBaseSize();
  49129. // Sprites
  49130. var deltaTime = engine.getDeltaTime();
  49131. var max = Math.min(this._capacity, this.sprites.length);
  49132. var rowSize = baseSize.width / this.cellWidth;
  49133. var offset = 0;
  49134. for (var index = 0; index < max; index++) {
  49135. var sprite = this.sprites[index];
  49136. if (!sprite) {
  49137. continue;
  49138. }
  49139. sprite._animate(deltaTime);
  49140. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49141. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49142. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49143. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49144. }
  49145. this._buffer.update(this._vertexData);
  49146. // Render
  49147. var effect = this._effectBase;
  49148. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49149. effect = this._effectFog;
  49150. }
  49151. engine.enableEffect(effect);
  49152. var viewMatrix = this._scene.getViewMatrix();
  49153. effect.setTexture("diffuseSampler", this._spriteTexture);
  49154. effect.setMatrix("view", viewMatrix);
  49155. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49156. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49157. // Fog
  49158. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49159. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49160. effect.setColor3("vFogColor", this._scene.fogColor);
  49161. }
  49162. // VBOs
  49163. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49164. // Draw order
  49165. engine.setDepthFunctionToLessOrEqual();
  49166. effect.setBool("alphaTest", true);
  49167. engine.setColorWrite(false);
  49168. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49169. engine.setColorWrite(true);
  49170. effect.setBool("alphaTest", false);
  49171. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49173. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49174. };
  49175. SpriteManager.prototype.dispose = function () {
  49176. if (this._buffer) {
  49177. this._buffer.dispose();
  49178. this._buffer = null;
  49179. }
  49180. if (this._indexBuffer) {
  49181. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49182. this._indexBuffer = null;
  49183. }
  49184. if (this._spriteTexture) {
  49185. this._spriteTexture.dispose();
  49186. this._spriteTexture = null;
  49187. }
  49188. // Remove from scene
  49189. var index = this._scene.spriteManagers.indexOf(this);
  49190. this._scene.spriteManagers.splice(index, 1);
  49191. // Callback
  49192. this.onDisposeObservable.notifyObservers(this);
  49193. this.onDisposeObservable.clear();
  49194. };
  49195. return SpriteManager;
  49196. }());
  49197. BABYLON.SpriteManager = SpriteManager;
  49198. })(BABYLON || (BABYLON = {}));
  49199. //# sourceMappingURL=babylon.spriteManager.js.map
  49200. var BABYLON;
  49201. (function (BABYLON) {
  49202. var Sprite = /** @class */ (function () {
  49203. function Sprite(name, manager) {
  49204. this.name = name;
  49205. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49206. this.width = 1.0;
  49207. this.height = 1.0;
  49208. this.angle = 0;
  49209. this.cellIndex = 0;
  49210. this.invertU = 0;
  49211. this.invertV = 0;
  49212. this.animations = new Array();
  49213. this.isPickable = false;
  49214. this._animationStarted = false;
  49215. this._loopAnimation = false;
  49216. this._fromIndex = 0;
  49217. this._toIndex = 0;
  49218. this._delay = 0;
  49219. this._direction = 1;
  49220. this._time = 0;
  49221. this._manager = manager;
  49222. this._manager.sprites.push(this);
  49223. this.position = BABYLON.Vector3.Zero();
  49224. }
  49225. Object.defineProperty(Sprite.prototype, "size", {
  49226. get: function () {
  49227. return this.width;
  49228. },
  49229. set: function (value) {
  49230. this.width = value;
  49231. this.height = value;
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49237. this._fromIndex = from;
  49238. this._toIndex = to;
  49239. this._loopAnimation = loop;
  49240. this._delay = delay;
  49241. this._animationStarted = true;
  49242. this._direction = from < to ? 1 : -1;
  49243. this.cellIndex = from;
  49244. this._time = 0;
  49245. this._onAnimationEnd = onAnimationEnd;
  49246. };
  49247. Sprite.prototype.stopAnimation = function () {
  49248. this._animationStarted = false;
  49249. };
  49250. Sprite.prototype._animate = function (deltaTime) {
  49251. if (!this._animationStarted)
  49252. return;
  49253. this._time += deltaTime;
  49254. if (this._time > this._delay) {
  49255. this._time = this._time % this._delay;
  49256. this.cellIndex += this._direction;
  49257. if (this.cellIndex > this._toIndex) {
  49258. if (this._loopAnimation) {
  49259. this.cellIndex = this._fromIndex;
  49260. }
  49261. else {
  49262. this.cellIndex = this._toIndex;
  49263. this._animationStarted = false;
  49264. if (this._onAnimationEnd) {
  49265. this._onAnimationEnd();
  49266. }
  49267. if (this.disposeWhenFinishedAnimating) {
  49268. this.dispose();
  49269. }
  49270. }
  49271. }
  49272. }
  49273. };
  49274. Sprite.prototype.dispose = function () {
  49275. for (var i = 0; i < this._manager.sprites.length; i++) {
  49276. if (this._manager.sprites[i] == this) {
  49277. this._manager.sprites.splice(i, 1);
  49278. }
  49279. }
  49280. };
  49281. return Sprite;
  49282. }());
  49283. BABYLON.Sprite = Sprite;
  49284. })(BABYLON || (BABYLON = {}));
  49285. //# sourceMappingURL=babylon.sprite.js.map
  49286. var BABYLON;
  49287. (function (BABYLON) {
  49288. var IntersectionInfo = /** @class */ (function () {
  49289. function IntersectionInfo(bu, bv, distance) {
  49290. this.bu = bu;
  49291. this.bv = bv;
  49292. this.distance = distance;
  49293. this.faceId = 0;
  49294. this.subMeshId = 0;
  49295. }
  49296. return IntersectionInfo;
  49297. }());
  49298. BABYLON.IntersectionInfo = IntersectionInfo;
  49299. var PickingInfo = /** @class */ (function () {
  49300. function PickingInfo() {
  49301. this.hit = false;
  49302. this.distance = 0;
  49303. this.pickedPoint = null;
  49304. this.pickedMesh = null;
  49305. this.bu = 0;
  49306. this.bv = 0;
  49307. this.faceId = -1;
  49308. this.subMeshId = 0;
  49309. this.pickedSprite = null;
  49310. }
  49311. // Methods
  49312. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49313. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49314. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49315. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49316. return null;
  49317. }
  49318. var indices = this.pickedMesh.getIndices();
  49319. if (!indices) {
  49320. return null;
  49321. }
  49322. var result;
  49323. if (useVerticesNormals) {
  49324. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49325. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49326. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49327. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49328. normal0 = normal0.scale(this.bu);
  49329. normal1 = normal1.scale(this.bv);
  49330. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49331. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49332. }
  49333. else {
  49334. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49335. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49336. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49337. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49338. var p1p2 = vertex1.subtract(vertex2);
  49339. var p3p2 = vertex3.subtract(vertex2);
  49340. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49341. }
  49342. if (useWorldCoordinates) {
  49343. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49344. }
  49345. return BABYLON.Vector3.Normalize(result);
  49346. };
  49347. PickingInfo.prototype.getTextureCoordinates = function () {
  49348. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49349. return null;
  49350. }
  49351. var indices = this.pickedMesh.getIndices();
  49352. if (!indices) {
  49353. return null;
  49354. }
  49355. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49356. if (!uvs) {
  49357. return null;
  49358. }
  49359. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49360. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49361. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49362. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49363. uv1 = uv1.scale(this.bu);
  49364. uv2 = uv2.scale(this.bv);
  49365. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49366. };
  49367. return PickingInfo;
  49368. }());
  49369. BABYLON.PickingInfo = PickingInfo;
  49370. })(BABYLON || (BABYLON = {}));
  49371. //# sourceMappingURL=babylon.pickingInfo.js.map
  49372. var BABYLON;
  49373. (function (BABYLON) {
  49374. var Ray = /** @class */ (function () {
  49375. function Ray(origin, direction, length) {
  49376. if (length === void 0) { length = Number.MAX_VALUE; }
  49377. this.origin = origin;
  49378. this.direction = direction;
  49379. this.length = length;
  49380. }
  49381. // Methods
  49382. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49383. var d = 0.0;
  49384. var maxValue = Number.MAX_VALUE;
  49385. var inv;
  49386. var min;
  49387. var max;
  49388. var temp;
  49389. if (Math.abs(this.direction.x) < 0.0000001) {
  49390. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49391. return false;
  49392. }
  49393. }
  49394. else {
  49395. inv = 1.0 / this.direction.x;
  49396. min = (minimum.x - this.origin.x) * inv;
  49397. max = (maximum.x - this.origin.x) * inv;
  49398. if (max === -Infinity) {
  49399. max = Infinity;
  49400. }
  49401. if (min > max) {
  49402. temp = min;
  49403. min = max;
  49404. max = temp;
  49405. }
  49406. d = Math.max(min, d);
  49407. maxValue = Math.min(max, maxValue);
  49408. if (d > maxValue) {
  49409. return false;
  49410. }
  49411. }
  49412. if (Math.abs(this.direction.y) < 0.0000001) {
  49413. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49414. return false;
  49415. }
  49416. }
  49417. else {
  49418. inv = 1.0 / this.direction.y;
  49419. min = (minimum.y - this.origin.y) * inv;
  49420. max = (maximum.y - this.origin.y) * inv;
  49421. if (max === -Infinity) {
  49422. max = Infinity;
  49423. }
  49424. if (min > max) {
  49425. temp = min;
  49426. min = max;
  49427. max = temp;
  49428. }
  49429. d = Math.max(min, d);
  49430. maxValue = Math.min(max, maxValue);
  49431. if (d > maxValue) {
  49432. return false;
  49433. }
  49434. }
  49435. if (Math.abs(this.direction.z) < 0.0000001) {
  49436. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49437. return false;
  49438. }
  49439. }
  49440. else {
  49441. inv = 1.0 / this.direction.z;
  49442. min = (minimum.z - this.origin.z) * inv;
  49443. max = (maximum.z - this.origin.z) * inv;
  49444. if (max === -Infinity) {
  49445. max = Infinity;
  49446. }
  49447. if (min > max) {
  49448. temp = min;
  49449. min = max;
  49450. max = temp;
  49451. }
  49452. d = Math.max(min, d);
  49453. maxValue = Math.min(max, maxValue);
  49454. if (d > maxValue) {
  49455. return false;
  49456. }
  49457. }
  49458. return true;
  49459. };
  49460. Ray.prototype.intersectsBox = function (box) {
  49461. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49462. };
  49463. Ray.prototype.intersectsSphere = function (sphere) {
  49464. var x = sphere.center.x - this.origin.x;
  49465. var y = sphere.center.y - this.origin.y;
  49466. var z = sphere.center.z - this.origin.z;
  49467. var pyth = (x * x) + (y * y) + (z * z);
  49468. var rr = sphere.radius * sphere.radius;
  49469. if (pyth <= rr) {
  49470. return true;
  49471. }
  49472. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49473. if (dot < 0.0) {
  49474. return false;
  49475. }
  49476. var temp = pyth - (dot * dot);
  49477. return temp <= rr;
  49478. };
  49479. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49480. if (!this._edge1) {
  49481. this._edge1 = BABYLON.Vector3.Zero();
  49482. this._edge2 = BABYLON.Vector3.Zero();
  49483. this._pvec = BABYLON.Vector3.Zero();
  49484. this._tvec = BABYLON.Vector3.Zero();
  49485. this._qvec = BABYLON.Vector3.Zero();
  49486. }
  49487. vertex1.subtractToRef(vertex0, this._edge1);
  49488. vertex2.subtractToRef(vertex0, this._edge2);
  49489. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49490. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49491. if (det === 0) {
  49492. return null;
  49493. }
  49494. var invdet = 1 / det;
  49495. this.origin.subtractToRef(vertex0, this._tvec);
  49496. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49497. if (bu < 0 || bu > 1.0) {
  49498. return null;
  49499. }
  49500. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49501. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49502. if (bv < 0 || bu + bv > 1.0) {
  49503. return null;
  49504. }
  49505. //check if the distance is longer than the predefined length.
  49506. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49507. if (distance > this.length) {
  49508. return null;
  49509. }
  49510. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49511. };
  49512. Ray.prototype.intersectsPlane = function (plane) {
  49513. var distance;
  49514. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49515. if (Math.abs(result1) < 9.99999997475243E-07) {
  49516. return null;
  49517. }
  49518. else {
  49519. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49520. distance = (-plane.d - result2) / result1;
  49521. if (distance < 0.0) {
  49522. if (distance < -9.99999997475243E-07) {
  49523. return null;
  49524. }
  49525. else {
  49526. return 0;
  49527. }
  49528. }
  49529. return distance;
  49530. }
  49531. };
  49532. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49533. var tm = BABYLON.Tmp.Matrix[0];
  49534. mesh.getWorldMatrix().invertToRef(tm);
  49535. if (this._tmpRay) {
  49536. Ray.TransformToRef(this, tm, this._tmpRay);
  49537. }
  49538. else {
  49539. this._tmpRay = Ray.Transform(this, tm);
  49540. }
  49541. return mesh.intersects(this._tmpRay, fastCheck);
  49542. };
  49543. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49544. if (results) {
  49545. results.length = 0;
  49546. }
  49547. else {
  49548. results = [];
  49549. }
  49550. for (var i = 0; i < meshes.length; i++) {
  49551. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49552. if (pickInfo.hit) {
  49553. results.push(pickInfo);
  49554. }
  49555. }
  49556. results.sort(this._comparePickingInfo);
  49557. return results;
  49558. };
  49559. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49560. if (pickingInfoA.distance < pickingInfoB.distance) {
  49561. return -1;
  49562. }
  49563. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49564. return 1;
  49565. }
  49566. else {
  49567. return 0;
  49568. }
  49569. };
  49570. /**
  49571. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49572. * @param sega the first point of the segment to test the intersection against
  49573. * @param segb the second point of the segment to test the intersection against
  49574. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49575. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49576. */
  49577. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49578. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49579. var u = segb.subtract(sega);
  49580. var v = rsegb.subtract(this.origin);
  49581. var w = sega.subtract(this.origin);
  49582. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49583. var b = BABYLON.Vector3.Dot(u, v);
  49584. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49585. var d = BABYLON.Vector3.Dot(u, w);
  49586. var e = BABYLON.Vector3.Dot(v, w);
  49587. var D = a * c - b * b; // always >= 0
  49588. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49589. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49590. // compute the line parameters of the two closest points
  49591. if (D < Ray.smallnum) {
  49592. sN = 0.0; // force using point P0 on segment S1
  49593. sD = 1.0; // to prevent possible division by 0.0 later
  49594. tN = e;
  49595. tD = c;
  49596. }
  49597. else {
  49598. sN = (b * e - c * d);
  49599. tN = (a * e - b * d);
  49600. if (sN < 0.0) {
  49601. sN = 0.0;
  49602. tN = e;
  49603. tD = c;
  49604. }
  49605. else if (sN > sD) {
  49606. sN = sD;
  49607. tN = e + b;
  49608. tD = c;
  49609. }
  49610. }
  49611. if (tN < 0.0) {
  49612. tN = 0.0;
  49613. // recompute sc for this edge
  49614. if (-d < 0.0) {
  49615. sN = 0.0;
  49616. }
  49617. else if (-d > a)
  49618. sN = sD;
  49619. else {
  49620. sN = -d;
  49621. sD = a;
  49622. }
  49623. }
  49624. else if (tN > tD) {
  49625. tN = tD;
  49626. // recompute sc for this edge
  49627. if ((-d + b) < 0.0) {
  49628. sN = 0;
  49629. }
  49630. else if ((-d + b) > a) {
  49631. sN = sD;
  49632. }
  49633. else {
  49634. sN = (-d + b);
  49635. sD = a;
  49636. }
  49637. }
  49638. // finally do the division to get sc and tc
  49639. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49640. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49641. // get the difference of the two closest points
  49642. var qtc = v.multiplyByFloats(tc, tc, tc);
  49643. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49644. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49645. if (isIntersected) {
  49646. return qtc.length();
  49647. }
  49648. return -1;
  49649. };
  49650. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49651. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49652. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49653. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49654. this.direction.normalize();
  49655. return this;
  49656. };
  49657. // Statics
  49658. Ray.Zero = function () {
  49659. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49660. };
  49661. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49662. var result = Ray.Zero();
  49663. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49664. };
  49665. /**
  49666. * 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
  49667. * transformed to the given world matrix.
  49668. * @param origin The origin point
  49669. * @param end The end point
  49670. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49671. */
  49672. Ray.CreateNewFromTo = function (origin, end, world) {
  49673. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49674. var direction = end.subtract(origin);
  49675. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49676. direction.normalize();
  49677. return Ray.Transform(new Ray(origin, direction, length), world);
  49678. };
  49679. Ray.Transform = function (ray, matrix) {
  49680. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49681. Ray.TransformToRef(ray, matrix, result);
  49682. return result;
  49683. };
  49684. Ray.TransformToRef = function (ray, matrix, result) {
  49685. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49686. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49687. result.length = ray.length;
  49688. var dir = result.direction;
  49689. var len = dir.length();
  49690. if (!(len === 0 || len === 1)) {
  49691. var num = 1.0 / len;
  49692. dir.x *= num;
  49693. dir.y *= num;
  49694. dir.z *= num;
  49695. result.length *= len;
  49696. }
  49697. };
  49698. Ray.smallnum = 0.00000001;
  49699. Ray.rayl = 10e8;
  49700. return Ray;
  49701. }());
  49702. BABYLON.Ray = Ray;
  49703. })(BABYLON || (BABYLON = {}));
  49704. //# sourceMappingURL=babylon.ray.js.map
  49705. var BABYLON;
  49706. (function (BABYLON) {
  49707. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49708. if (boxMin.x > sphereCenter.x + sphereRadius)
  49709. return false;
  49710. if (sphereCenter.x - sphereRadius > boxMax.x)
  49711. return false;
  49712. if (boxMin.y > sphereCenter.y + sphereRadius)
  49713. return false;
  49714. if (sphereCenter.y - sphereRadius > boxMax.y)
  49715. return false;
  49716. if (boxMin.z > sphereCenter.z + sphereRadius)
  49717. return false;
  49718. if (sphereCenter.z - sphereRadius > boxMax.z)
  49719. return false;
  49720. return true;
  49721. };
  49722. var getLowestRoot = (function () {
  49723. var result = { root: 0, found: false };
  49724. return function (a, b, c, maxR) {
  49725. result.root = 0;
  49726. result.found = false;
  49727. var determinant = b * b - 4.0 * a * c;
  49728. if (determinant < 0)
  49729. return result;
  49730. var sqrtD = Math.sqrt(determinant);
  49731. var r1 = (-b - sqrtD) / (2.0 * a);
  49732. var r2 = (-b + sqrtD) / (2.0 * a);
  49733. if (r1 > r2) {
  49734. var temp = r2;
  49735. r2 = r1;
  49736. r1 = temp;
  49737. }
  49738. if (r1 > 0 && r1 < maxR) {
  49739. result.root = r1;
  49740. result.found = true;
  49741. return result;
  49742. }
  49743. if (r2 > 0 && r2 < maxR) {
  49744. result.root = r2;
  49745. result.found = true;
  49746. return result;
  49747. }
  49748. return result;
  49749. };
  49750. })();
  49751. var Collider = /** @class */ (function () {
  49752. function Collider() {
  49753. this._collisionPoint = BABYLON.Vector3.Zero();
  49754. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49755. this._tempVector = BABYLON.Vector3.Zero();
  49756. this._tempVector2 = BABYLON.Vector3.Zero();
  49757. this._tempVector3 = BABYLON.Vector3.Zero();
  49758. this._tempVector4 = BABYLON.Vector3.Zero();
  49759. this._edge = BABYLON.Vector3.Zero();
  49760. this._baseToVertex = BABYLON.Vector3.Zero();
  49761. this._destinationPoint = BABYLON.Vector3.Zero();
  49762. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49763. this._displacementVector = BABYLON.Vector3.Zero();
  49764. this._radius = BABYLON.Vector3.One();
  49765. this._retry = 0;
  49766. this._basePointWorld = BABYLON.Vector3.Zero();
  49767. this._velocityWorld = BABYLON.Vector3.Zero();
  49768. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49769. this._collisionMask = -1;
  49770. }
  49771. Object.defineProperty(Collider.prototype, "collisionMask", {
  49772. get: function () {
  49773. return this._collisionMask;
  49774. },
  49775. set: function (mask) {
  49776. this._collisionMask = !isNaN(mask) ? mask : -1;
  49777. },
  49778. enumerable: true,
  49779. configurable: true
  49780. });
  49781. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49782. /**
  49783. * Gets the plane normal used to compute the sliding response (in local space)
  49784. */
  49785. get: function () {
  49786. return this._slidePlaneNormal;
  49787. },
  49788. enumerable: true,
  49789. configurable: true
  49790. });
  49791. // Methods
  49792. Collider.prototype._initialize = function (source, dir, e) {
  49793. this._velocity = dir;
  49794. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49795. this._basePoint = source;
  49796. source.multiplyToRef(this._radius, this._basePointWorld);
  49797. dir.multiplyToRef(this._radius, this._velocityWorld);
  49798. this._velocityWorldLength = this._velocityWorld.length();
  49799. this._epsilon = e;
  49800. this.collisionFound = false;
  49801. };
  49802. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49803. pa.subtractToRef(point, this._tempVector);
  49804. pb.subtractToRef(point, this._tempVector2);
  49805. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49806. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49807. if (d < 0)
  49808. return false;
  49809. pc.subtractToRef(point, this._tempVector3);
  49810. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49811. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49812. if (d < 0)
  49813. return false;
  49814. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49815. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49816. return d >= 0;
  49817. };
  49818. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49819. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49820. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49821. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49822. return false;
  49823. }
  49824. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49825. return false;
  49826. return true;
  49827. };
  49828. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49829. var t0;
  49830. var embeddedInPlane = false;
  49831. //defensive programming, actually not needed.
  49832. if (!trianglePlaneArray) {
  49833. trianglePlaneArray = [];
  49834. }
  49835. if (!trianglePlaneArray[faceIndex]) {
  49836. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49837. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49838. }
  49839. var trianglePlane = trianglePlaneArray[faceIndex];
  49840. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49841. return;
  49842. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49843. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49844. if (normalDotVelocity == 0) {
  49845. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49846. return;
  49847. embeddedInPlane = true;
  49848. t0 = 0;
  49849. }
  49850. else {
  49851. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49852. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49853. if (t0 > t1) {
  49854. var temp = t1;
  49855. t1 = t0;
  49856. t0 = temp;
  49857. }
  49858. if (t0 > 1.0 || t1 < 0.0)
  49859. return;
  49860. if (t0 < 0)
  49861. t0 = 0;
  49862. if (t0 > 1.0)
  49863. t0 = 1.0;
  49864. }
  49865. this._collisionPoint.copyFromFloats(0, 0, 0);
  49866. var found = false;
  49867. var t = 1.0;
  49868. if (!embeddedInPlane) {
  49869. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49870. this._velocity.scaleToRef(t0, this._tempVector);
  49871. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49872. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49873. found = true;
  49874. t = t0;
  49875. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49876. }
  49877. }
  49878. if (!found) {
  49879. var velocitySquaredLength = this._velocity.lengthSquared();
  49880. var a = velocitySquaredLength;
  49881. this._basePoint.subtractToRef(p1, this._tempVector);
  49882. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49883. var c = this._tempVector.lengthSquared() - 1.0;
  49884. var lowestRoot = getLowestRoot(a, b, c, t);
  49885. if (lowestRoot.found) {
  49886. t = lowestRoot.root;
  49887. found = true;
  49888. this._collisionPoint.copyFrom(p1);
  49889. }
  49890. this._basePoint.subtractToRef(p2, this._tempVector);
  49891. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49892. c = this._tempVector.lengthSquared() - 1.0;
  49893. lowestRoot = getLowestRoot(a, b, c, t);
  49894. if (lowestRoot.found) {
  49895. t = lowestRoot.root;
  49896. found = true;
  49897. this._collisionPoint.copyFrom(p2);
  49898. }
  49899. this._basePoint.subtractToRef(p3, this._tempVector);
  49900. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49901. c = this._tempVector.lengthSquared() - 1.0;
  49902. lowestRoot = getLowestRoot(a, b, c, t);
  49903. if (lowestRoot.found) {
  49904. t = lowestRoot.root;
  49905. found = true;
  49906. this._collisionPoint.copyFrom(p3);
  49907. }
  49908. p2.subtractToRef(p1, this._edge);
  49909. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49910. var edgeSquaredLength = this._edge.lengthSquared();
  49911. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49912. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49913. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49914. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49915. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49916. lowestRoot = getLowestRoot(a, b, c, t);
  49917. if (lowestRoot.found) {
  49918. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49919. if (f >= 0.0 && f <= 1.0) {
  49920. t = lowestRoot.root;
  49921. found = true;
  49922. this._edge.scaleInPlace(f);
  49923. p1.addToRef(this._edge, this._collisionPoint);
  49924. }
  49925. }
  49926. p3.subtractToRef(p2, this._edge);
  49927. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49928. edgeSquaredLength = this._edge.lengthSquared();
  49929. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49930. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49931. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49932. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49933. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49934. lowestRoot = getLowestRoot(a, b, c, t);
  49935. if (lowestRoot.found) {
  49936. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49937. if (f >= 0.0 && f <= 1.0) {
  49938. t = lowestRoot.root;
  49939. found = true;
  49940. this._edge.scaleInPlace(f);
  49941. p2.addToRef(this._edge, this._collisionPoint);
  49942. }
  49943. }
  49944. p1.subtractToRef(p3, this._edge);
  49945. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49946. edgeSquaredLength = this._edge.lengthSquared();
  49947. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49948. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49949. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49950. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49951. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49952. lowestRoot = getLowestRoot(a, b, c, t);
  49953. if (lowestRoot.found) {
  49954. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49955. if (f >= 0.0 && f <= 1.0) {
  49956. t = lowestRoot.root;
  49957. found = true;
  49958. this._edge.scaleInPlace(f);
  49959. p3.addToRef(this._edge, this._collisionPoint);
  49960. }
  49961. }
  49962. }
  49963. if (found) {
  49964. var distToCollision = t * this._velocity.length();
  49965. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49966. if (!this.intersectionPoint) {
  49967. this.intersectionPoint = this._collisionPoint.clone();
  49968. }
  49969. else {
  49970. this.intersectionPoint.copyFrom(this._collisionPoint);
  49971. }
  49972. this._nearestDistance = distToCollision;
  49973. this.collisionFound = true;
  49974. }
  49975. }
  49976. };
  49977. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49978. for (var i = indexStart; i < indexEnd; i += 3) {
  49979. var p1 = pts[indices[i] - decal];
  49980. var p2 = pts[indices[i + 1] - decal];
  49981. var p3 = pts[indices[i + 2] - decal];
  49982. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49983. }
  49984. };
  49985. Collider.prototype._getResponse = function (pos, vel) {
  49986. pos.addToRef(vel, this._destinationPoint);
  49987. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49988. this._basePoint.addToRef(vel, pos);
  49989. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49990. this._slidePlaneNormal.normalize();
  49991. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49992. pos.addInPlace(this._displacementVector);
  49993. this.intersectionPoint.addInPlace(this._displacementVector);
  49994. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49995. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49996. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49997. };
  49998. return Collider;
  49999. }());
  50000. BABYLON.Collider = Collider;
  50001. })(BABYLON || (BABYLON = {}));
  50002. //# sourceMappingURL=babylon.collider.js.map
  50003. var BABYLON;
  50004. (function (BABYLON) {
  50005. //WebWorker code will be inserted to this variable.
  50006. BABYLON.CollisionWorker = "";
  50007. var WorkerTaskType;
  50008. (function (WorkerTaskType) {
  50009. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50010. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50011. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50012. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50013. var WorkerReplyType;
  50014. (function (WorkerReplyType) {
  50015. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50016. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50017. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50018. var CollisionCoordinatorWorker = /** @class */ (function () {
  50019. function CollisionCoordinatorWorker() {
  50020. var _this = this;
  50021. this._scaledPosition = BABYLON.Vector3.Zero();
  50022. this._scaledVelocity = BABYLON.Vector3.Zero();
  50023. this.onMeshUpdated = function (transformNode) {
  50024. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50025. };
  50026. this.onGeometryUpdated = function (geometry) {
  50027. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50028. };
  50029. this._afterRender = function () {
  50030. if (!_this._init)
  50031. return;
  50032. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50033. return;
  50034. }
  50035. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50036. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50037. if (_this._runningUpdated > 4) {
  50038. return;
  50039. }
  50040. ++_this._runningUpdated;
  50041. var payload = {
  50042. updatedMeshes: _this._addUpdateMeshesList,
  50043. updatedGeometries: _this._addUpdateGeometriesList,
  50044. removedGeometries: _this._toRemoveGeometryArray,
  50045. removedMeshes: _this._toRemoveMeshesArray
  50046. };
  50047. var message = {
  50048. payload: payload,
  50049. taskType: WorkerTaskType.UPDATE
  50050. };
  50051. var serializable = [];
  50052. for (var id in payload.updatedGeometries) {
  50053. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50054. //prepare transferables
  50055. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50056. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50057. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50058. }
  50059. }
  50060. _this._worker.postMessage(message, serializable);
  50061. _this._addUpdateMeshesList = {};
  50062. _this._addUpdateGeometriesList = {};
  50063. _this._toRemoveGeometryArray = [];
  50064. _this._toRemoveMeshesArray = [];
  50065. };
  50066. this._onMessageFromWorker = function (e) {
  50067. var returnData = e.data;
  50068. if (returnData.error != WorkerReplyType.SUCCESS) {
  50069. //TODO what errors can be returned from the worker?
  50070. BABYLON.Tools.Warn("error returned from worker!");
  50071. return;
  50072. }
  50073. switch (returnData.taskType) {
  50074. case WorkerTaskType.INIT:
  50075. _this._init = true;
  50076. //Update the worked with ALL of the scene's current state
  50077. _this._scene.meshes.forEach(function (mesh) {
  50078. _this.onMeshAdded(mesh);
  50079. });
  50080. _this._scene.getGeometries().forEach(function (geometry) {
  50081. _this.onGeometryAdded(geometry);
  50082. });
  50083. break;
  50084. case WorkerTaskType.UPDATE:
  50085. _this._runningUpdated--;
  50086. break;
  50087. case WorkerTaskType.COLLIDE:
  50088. var returnPayload = returnData.payload;
  50089. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50090. return;
  50091. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50092. if (callback) {
  50093. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50094. if (mesh) {
  50095. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50096. }
  50097. }
  50098. //cleanup
  50099. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50100. break;
  50101. }
  50102. };
  50103. this._collisionsCallbackArray = [];
  50104. this._init = false;
  50105. this._runningUpdated = 0;
  50106. this._addUpdateMeshesList = {};
  50107. this._addUpdateGeometriesList = {};
  50108. this._toRemoveGeometryArray = [];
  50109. this._toRemoveMeshesArray = [];
  50110. }
  50111. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50112. if (!this._init)
  50113. return;
  50114. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50115. return;
  50116. position.divideToRef(collider._radius, this._scaledPosition);
  50117. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50118. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50119. var payload = {
  50120. collider: {
  50121. position: this._scaledPosition.asArray(),
  50122. velocity: this._scaledVelocity.asArray(),
  50123. radius: collider._radius.asArray()
  50124. },
  50125. collisionId: collisionIndex,
  50126. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50127. maximumRetry: maximumRetry
  50128. };
  50129. var message = {
  50130. payload: payload,
  50131. taskType: WorkerTaskType.COLLIDE
  50132. };
  50133. this._worker.postMessage(message);
  50134. };
  50135. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50136. this._scene = scene;
  50137. this._scene.registerAfterRender(this._afterRender);
  50138. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50139. this._worker = new Worker(workerUrl);
  50140. this._worker.onmessage = this._onMessageFromWorker;
  50141. var message = {
  50142. payload: {},
  50143. taskType: WorkerTaskType.INIT
  50144. };
  50145. this._worker.postMessage(message);
  50146. };
  50147. CollisionCoordinatorWorker.prototype.destroy = function () {
  50148. this._scene.unregisterAfterRender(this._afterRender);
  50149. this._worker.terminate();
  50150. };
  50151. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50152. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50153. this.onMeshUpdated(mesh);
  50154. };
  50155. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50156. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50157. };
  50158. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50159. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50160. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50161. this.onGeometryUpdated(geometry);
  50162. };
  50163. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50164. this._toRemoveGeometryArray.push(geometry.id);
  50165. };
  50166. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50167. var submeshes = [];
  50168. if (mesh.subMeshes) {
  50169. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50170. var boundingInfo = sm.getBoundingInfo();
  50171. return {
  50172. position: idx,
  50173. verticesStart: sm.verticesStart,
  50174. verticesCount: sm.verticesCount,
  50175. indexStart: sm.indexStart,
  50176. indexCount: sm.indexCount,
  50177. hasMaterial: !!sm.getMaterial(),
  50178. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50179. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50180. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50181. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50182. };
  50183. });
  50184. }
  50185. var geometryId = null;
  50186. if (mesh instanceof BABYLON.Mesh) {
  50187. var geometry = mesh.geometry;
  50188. geometryId = geometry ? geometry.id : null;
  50189. }
  50190. else if (mesh instanceof BABYLON.InstancedMesh) {
  50191. var geometry = mesh.sourceMesh.geometry;
  50192. geometryId = geometry ? geometry.id : null;
  50193. }
  50194. var boundingInfo = mesh.getBoundingInfo();
  50195. return {
  50196. uniqueId: mesh.uniqueId,
  50197. id: mesh.id,
  50198. name: mesh.name,
  50199. geometryId: geometryId,
  50200. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50201. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50202. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50203. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50204. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50205. subMeshes: submeshes,
  50206. checkCollisions: mesh.checkCollisions
  50207. };
  50208. };
  50209. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50210. return {
  50211. id: geometry.id,
  50212. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50213. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50214. indices: new Uint32Array(geometry.getIndices() || []),
  50215. };
  50216. };
  50217. return CollisionCoordinatorWorker;
  50218. }());
  50219. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50220. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50221. function CollisionCoordinatorLegacy() {
  50222. this._scaledPosition = BABYLON.Vector3.Zero();
  50223. this._scaledVelocity = BABYLON.Vector3.Zero();
  50224. this._finalPosition = BABYLON.Vector3.Zero();
  50225. }
  50226. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50227. position.divideToRef(collider._radius, this._scaledPosition);
  50228. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50229. collider.collidedMesh = null;
  50230. collider._retry = 0;
  50231. collider._initialVelocity = this._scaledVelocity;
  50232. collider._initialPosition = this._scaledPosition;
  50233. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50234. this._finalPosition.multiplyInPlace(collider._radius);
  50235. //run the callback
  50236. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50237. };
  50238. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50239. this._scene = scene;
  50240. };
  50241. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50242. //Legacy need no destruction method.
  50243. };
  50244. //No update in legacy mode
  50245. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50246. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50247. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50248. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50249. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50250. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50251. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50252. if (excludedMesh === void 0) { excludedMesh = null; }
  50253. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50254. if (collider._retry >= maximumRetry) {
  50255. finalPosition.copyFrom(position);
  50256. return;
  50257. }
  50258. // Check if this is a mesh else camera or -1
  50259. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50260. collider._initialize(position, velocity, closeDistance);
  50261. // Check all meshes
  50262. for (var index = 0; index < this._scene.meshes.length; index++) {
  50263. var mesh = this._scene.meshes[index];
  50264. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50265. mesh._checkCollision(collider);
  50266. }
  50267. }
  50268. if (!collider.collisionFound) {
  50269. position.addToRef(velocity, finalPosition);
  50270. return;
  50271. }
  50272. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50273. collider._getResponse(position, velocity);
  50274. }
  50275. if (velocity.length() <= closeDistance) {
  50276. finalPosition.copyFrom(position);
  50277. return;
  50278. }
  50279. collider._retry++;
  50280. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50281. };
  50282. return CollisionCoordinatorLegacy;
  50283. }());
  50284. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50285. })(BABYLON || (BABYLON = {}));
  50286. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50287. var BABYLON;
  50288. (function (BABYLON) {
  50289. /**
  50290. * A particle represents one of the element emitted by a particle system.
  50291. * This is mainly define by its coordinates, direction, velocity and age.
  50292. */
  50293. var Particle = /** @class */ (function () {
  50294. /**
  50295. * Creates a new instance of @see Particle
  50296. * @param particleSystem the particle system the particle belongs to
  50297. */
  50298. function Particle(particleSystem) {
  50299. this.particleSystem = particleSystem;
  50300. /**
  50301. * The world position of the particle in the scene.
  50302. */
  50303. this.position = BABYLON.Vector3.Zero();
  50304. /**
  50305. * The world direction of the particle in the scene.
  50306. */
  50307. this.direction = BABYLON.Vector3.Zero();
  50308. /**
  50309. * The color of the particle.
  50310. */
  50311. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50312. /**
  50313. * The color change of the particle per step.
  50314. */
  50315. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50316. /**
  50317. * Defines how long will the life of the particle be.
  50318. */
  50319. this.lifeTime = 1.0;
  50320. /**
  50321. * The current age of the particle.
  50322. */
  50323. this.age = 0;
  50324. /**
  50325. * The current size of the particle.
  50326. */
  50327. this.size = 0;
  50328. /**
  50329. * The current angle of the particle.
  50330. */
  50331. this.angle = 0;
  50332. /**
  50333. * Defines how fast is the angle changing.
  50334. */
  50335. this.angularSpeed = 0;
  50336. /**
  50337. * Defines the cell index used by the particle to be rendered from a sprite.
  50338. */
  50339. this.cellIndex = 0;
  50340. this._currentFrameCounter = 0;
  50341. if (!this.particleSystem.isAnimationSheetEnabled) {
  50342. return;
  50343. }
  50344. this.cellIndex = this.particleSystem.startSpriteCellID;
  50345. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50346. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50347. }
  50348. else {
  50349. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50350. }
  50351. }
  50352. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50353. // (ageOffset / scaledUpdateSpeed) / available cells
  50354. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50355. this._currentFrameCounter += scaledUpdateSpeed;
  50356. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50357. this._currentFrameCounter = 0;
  50358. this.cellIndex++;
  50359. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50360. this.cellIndex = this.particleSystem.endSpriteCellID;
  50361. }
  50362. }
  50363. };
  50364. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50365. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50366. this.cellIndex++;
  50367. this._currentFrameCounter = 0;
  50368. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50369. if (this.particleSystem.spriteCellLoop) {
  50370. this.cellIndex = this.particleSystem.startSpriteCellID;
  50371. }
  50372. else {
  50373. this.cellIndex = this.particleSystem.endSpriteCellID;
  50374. }
  50375. }
  50376. }
  50377. else {
  50378. this._currentFrameCounter++;
  50379. }
  50380. };
  50381. /**
  50382. * Copy the properties of particle to another one.
  50383. * @param other the particle to copy the information to.
  50384. */
  50385. Particle.prototype.copyTo = function (other) {
  50386. other.position.copyFrom(this.position);
  50387. other.direction.copyFrom(this.direction);
  50388. other.color.copyFrom(this.color);
  50389. other.colorStep.copyFrom(this.colorStep);
  50390. other.lifeTime = this.lifeTime;
  50391. other.age = this.age;
  50392. other.size = this.size;
  50393. other.angle = this.angle;
  50394. other.angularSpeed = this.angularSpeed;
  50395. other.particleSystem = this.particleSystem;
  50396. other.cellIndex = this.cellIndex;
  50397. };
  50398. return Particle;
  50399. }());
  50400. BABYLON.Particle = Particle;
  50401. })(BABYLON || (BABYLON = {}));
  50402. //# sourceMappingURL=babylon.particle.js.map
  50403. var BABYLON;
  50404. (function (BABYLON) {
  50405. /**
  50406. * This represents a particle system in Babylon.
  50407. * 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.
  50408. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50409. * @example https://doc.babylonjs.com/babylon101/particles
  50410. */
  50411. var ParticleSystem = /** @class */ (function () {
  50412. /**
  50413. * Instantiates a particle system.
  50414. * 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.
  50415. * @param name The name of the particle system
  50416. * @param capacity The max number of particles alive at the same time
  50417. * @param scene The scene the particle system belongs to
  50418. * @param customEffect a custom effect used to change the way particles are rendered by default
  50419. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50420. * @param epsilon Offset used to render the particles
  50421. */
  50422. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50423. if (customEffect === void 0) { customEffect = null; }
  50424. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50425. if (epsilon === void 0) { epsilon = 0.01; }
  50426. var _this = this;
  50427. /**
  50428. * List of animations used by the particle system.
  50429. */
  50430. this.animations = [];
  50431. /**
  50432. * The rendering group used by the Particle system to chose when to render.
  50433. */
  50434. this.renderingGroupId = 0;
  50435. /**
  50436. * The emitter represents the Mesh or position we are attaching the particle system to.
  50437. */
  50438. this.emitter = null;
  50439. /**
  50440. * The maximum number of particles to emit per frame
  50441. */
  50442. this.emitRate = 10;
  50443. /**
  50444. * If you want to launch only a few particles at once, that can be done, as well.
  50445. */
  50446. this.manualEmitCount = -1;
  50447. /**
  50448. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50449. */
  50450. this.updateSpeed = 0.01;
  50451. /**
  50452. * The amount of time the particle system is running (depends of the overall update speed).
  50453. */
  50454. this.targetStopDuration = 0;
  50455. /**
  50456. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50457. */
  50458. this.disposeOnStop = false;
  50459. /**
  50460. * Minimum power of emitting particles.
  50461. */
  50462. this.minEmitPower = 1;
  50463. /**
  50464. * Maximum power of emitting particles.
  50465. */
  50466. this.maxEmitPower = 1;
  50467. /**
  50468. * Minimum life time of emitting particles.
  50469. */
  50470. this.minLifeTime = 1;
  50471. /**
  50472. * Maximum life time of emitting particles.
  50473. */
  50474. this.maxLifeTime = 1;
  50475. /**
  50476. * Minimum Size of emitting particles.
  50477. */
  50478. this.minSize = 1;
  50479. /**
  50480. * Maximum Size of emitting particles.
  50481. */
  50482. this.maxSize = 1;
  50483. /**
  50484. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50485. */
  50486. this.minAngularSpeed = 0;
  50487. /**
  50488. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50489. */
  50490. this.maxAngularSpeed = 0;
  50491. /**
  50492. * The layer mask we are rendering the particles through.
  50493. */
  50494. this.layerMask = 0x0FFFFFFF;
  50495. /**
  50496. * This can help using your own shader to render the particle system.
  50497. * The according effect will be created
  50498. */
  50499. this.customShader = null;
  50500. /**
  50501. * By default particle system starts as soon as they are created. This prevents the
  50502. * automatic start to happen and let you decide when to start emitting particles.
  50503. */
  50504. this.preventAutoStart = false;
  50505. /**
  50506. * Callback triggered when the particle animation is ending.
  50507. */
  50508. this.onAnimationEnd = null;
  50509. /**
  50510. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50511. */
  50512. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50513. /**
  50514. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50515. * to override the particles.
  50516. */
  50517. this.forceDepthWrite = false;
  50518. /**
  50519. * You can use gravity if you want to give an orientation to your particles.
  50520. */
  50521. this.gravity = BABYLON.Vector3.Zero();
  50522. /**
  50523. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50524. */
  50525. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50526. /**
  50527. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50528. */
  50529. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50530. /**
  50531. * Color the particle will have at the end of its lifetime.
  50532. */
  50533. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50534. /**
  50535. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50536. */
  50537. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50538. /**
  50539. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50540. */
  50541. this.spriteCellLoop = true;
  50542. /**
  50543. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50544. */
  50545. this.spriteCellChangeSpeed = 0;
  50546. /**
  50547. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50548. */
  50549. this.startSpriteCellID = 0;
  50550. /**
  50551. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50552. */
  50553. this.endSpriteCellID = 0;
  50554. /**
  50555. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50556. */
  50557. this.spriteCellWidth = 0;
  50558. /**
  50559. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50560. */
  50561. this.spriteCellHeight = 0;
  50562. /**
  50563. * An event triggered when the system is disposed.
  50564. */
  50565. this.onDisposeObservable = new BABYLON.Observable();
  50566. this._particles = new Array();
  50567. this._stockParticles = new Array();
  50568. this._newPartsExcess = 0;
  50569. this._vertexBuffers = {};
  50570. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50571. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50572. this._scaledDirection = BABYLON.Vector3.Zero();
  50573. this._scaledGravity = BABYLON.Vector3.Zero();
  50574. this._currentRenderId = -1;
  50575. this._started = false;
  50576. this._stopped = false;
  50577. this._actualFrame = 0;
  50578. this._vertexBufferSize = 11;
  50579. this._appendParticleVertexes = null;
  50580. this.id = name;
  50581. this.name = name;
  50582. this._capacity = capacity;
  50583. this._epsilon = epsilon;
  50584. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50585. if (isAnimationSheetEnabled) {
  50586. this._vertexBufferSize = 12;
  50587. }
  50588. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50589. this._customEffect = customEffect;
  50590. scene.particleSystems.push(this);
  50591. this._createIndexBuffer();
  50592. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50593. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50594. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50595. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50596. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50597. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50598. if (this._isAnimationSheetEnabled) {
  50599. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50600. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50601. }
  50602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50603. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50604. this._vertexBuffers["options"] = options;
  50605. // Default emitter type
  50606. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50607. this.updateFunction = function (particles) {
  50608. for (var index = 0; index < particles.length; index++) {
  50609. var particle = particles[index];
  50610. particle.age += _this._scaledUpdateSpeed;
  50611. if (particle.age >= particle.lifeTime) {
  50612. _this.recycleParticle(particle);
  50613. index--;
  50614. continue;
  50615. }
  50616. else {
  50617. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50618. particle.color.addInPlace(_this._scaledColorStep);
  50619. if (particle.color.a < 0)
  50620. particle.color.a = 0;
  50621. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50622. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50623. particle.position.addInPlace(_this._scaledDirection);
  50624. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50625. particle.direction.addInPlace(_this._scaledGravity);
  50626. if (_this._isAnimationSheetEnabled) {
  50627. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50628. }
  50629. }
  50630. }
  50631. };
  50632. }
  50633. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50634. /**
  50635. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50636. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50637. */
  50638. get: function () {
  50639. if (this.particleEmitterType.direction1) {
  50640. return this.particleEmitterType.direction1;
  50641. }
  50642. return BABYLON.Vector3.Zero();
  50643. },
  50644. set: function (value) {
  50645. if (this.particleEmitterType.direction1) {
  50646. this.particleEmitterType.direction1 = value;
  50647. }
  50648. },
  50649. enumerable: true,
  50650. configurable: true
  50651. });
  50652. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50653. /**
  50654. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50655. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50656. */
  50657. get: function () {
  50658. if (this.particleEmitterType.direction2) {
  50659. return this.particleEmitterType.direction2;
  50660. }
  50661. return BABYLON.Vector3.Zero();
  50662. },
  50663. set: function (value) {
  50664. if (this.particleEmitterType.direction2) {
  50665. this.particleEmitterType.direction2 = value;
  50666. }
  50667. },
  50668. enumerable: true,
  50669. configurable: true
  50670. });
  50671. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50672. /**
  50673. * 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.
  50674. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50675. */
  50676. get: function () {
  50677. if (this.particleEmitterType.minEmitBox) {
  50678. return this.particleEmitterType.minEmitBox;
  50679. }
  50680. return BABYLON.Vector3.Zero();
  50681. },
  50682. set: function (value) {
  50683. if (this.particleEmitterType.minEmitBox) {
  50684. this.particleEmitterType.minEmitBox = value;
  50685. }
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50691. /**
  50692. * 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.
  50693. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50694. */
  50695. get: function () {
  50696. if (this.particleEmitterType.maxEmitBox) {
  50697. return this.particleEmitterType.maxEmitBox;
  50698. }
  50699. return BABYLON.Vector3.Zero();
  50700. },
  50701. set: function (value) {
  50702. if (this.particleEmitterType.maxEmitBox) {
  50703. this.particleEmitterType.maxEmitBox = value;
  50704. }
  50705. },
  50706. enumerable: true,
  50707. configurable: true
  50708. });
  50709. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50710. /**
  50711. * Sets a callback that will be triggered when the system is disposed.
  50712. */
  50713. set: function (callback) {
  50714. if (this._onDisposeObserver) {
  50715. this.onDisposeObservable.remove(this._onDisposeObserver);
  50716. }
  50717. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50723. /**
  50724. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50725. */
  50726. get: function () {
  50727. return this._isAnimationSheetEnabled;
  50728. },
  50729. enumerable: true,
  50730. configurable: true
  50731. });
  50732. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50733. /**
  50734. * Gets the current list of active particles
  50735. */
  50736. get: function () {
  50737. return this._particles;
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. /**
  50743. * Returns the string "ParticleSystem"
  50744. * @returns a string containing the class name
  50745. */
  50746. ParticleSystem.prototype.getClassName = function () {
  50747. return "ParticleSystem";
  50748. };
  50749. ParticleSystem.prototype._createIndexBuffer = function () {
  50750. var indices = [];
  50751. var index = 0;
  50752. for (var count = 0; count < this._capacity; count++) {
  50753. indices.push(index);
  50754. indices.push(index + 1);
  50755. indices.push(index + 2);
  50756. indices.push(index);
  50757. indices.push(index + 2);
  50758. indices.push(index + 3);
  50759. index += 4;
  50760. }
  50761. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50762. };
  50763. /**
  50764. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50765. * Its lifetime will start back at 0.
  50766. * @param particle The particle to recycle
  50767. */
  50768. ParticleSystem.prototype.recycleParticle = function (particle) {
  50769. var lastParticle = this._particles.pop();
  50770. if (lastParticle !== particle) {
  50771. lastParticle.copyTo(particle);
  50772. this._stockParticles.push(lastParticle);
  50773. }
  50774. };
  50775. /**
  50776. * Gets the maximum number of particles active at the same time.
  50777. * @returns The max number of active particles.
  50778. */
  50779. ParticleSystem.prototype.getCapacity = function () {
  50780. return this._capacity;
  50781. };
  50782. /**
  50783. * Gets Wether there are still active particles in the system.
  50784. * @returns True if it is alive, otherwise false.
  50785. */
  50786. ParticleSystem.prototype.isAlive = function () {
  50787. return this._alive;
  50788. };
  50789. /**
  50790. * Gets Wether the system has been started.
  50791. * @returns True if it has been started, otherwise false.
  50792. */
  50793. ParticleSystem.prototype.isStarted = function () {
  50794. return this._started;
  50795. };
  50796. /**
  50797. * Starts the particle system and begins to emit.
  50798. */
  50799. ParticleSystem.prototype.start = function () {
  50800. this._started = true;
  50801. this._stopped = false;
  50802. this._actualFrame = 0;
  50803. };
  50804. /**
  50805. * Stops the particle system.
  50806. */
  50807. ParticleSystem.prototype.stop = function () {
  50808. this._stopped = true;
  50809. };
  50810. /**
  50811. * Remove all active particles
  50812. */
  50813. ParticleSystem.prototype.reset = function () {
  50814. this._stockParticles = [];
  50815. this._particles = [];
  50816. };
  50817. /**
  50818. * @ignore (for internal use only)
  50819. */
  50820. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50821. var offset = index * this._vertexBufferSize;
  50822. this._vertexData[offset] = particle.position.x;
  50823. this._vertexData[offset + 1] = particle.position.y;
  50824. this._vertexData[offset + 2] = particle.position.z;
  50825. this._vertexData[offset + 3] = particle.color.r;
  50826. this._vertexData[offset + 4] = particle.color.g;
  50827. this._vertexData[offset + 5] = particle.color.b;
  50828. this._vertexData[offset + 6] = particle.color.a;
  50829. this._vertexData[offset + 7] = particle.angle;
  50830. this._vertexData[offset + 8] = particle.size;
  50831. this._vertexData[offset + 9] = offsetX;
  50832. this._vertexData[offset + 10] = offsetY;
  50833. };
  50834. /**
  50835. * @ignore (for internal use only)
  50836. */
  50837. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50838. if (offsetX === 0)
  50839. offsetX = this._epsilon;
  50840. else if (offsetX === 1)
  50841. offsetX = 1 - this._epsilon;
  50842. if (offsetY === 0)
  50843. offsetY = this._epsilon;
  50844. else if (offsetY === 1)
  50845. offsetY = 1 - this._epsilon;
  50846. var offset = index * this._vertexBufferSize;
  50847. this._vertexData[offset] = particle.position.x;
  50848. this._vertexData[offset + 1] = particle.position.y;
  50849. this._vertexData[offset + 2] = particle.position.z;
  50850. this._vertexData[offset + 3] = particle.color.r;
  50851. this._vertexData[offset + 4] = particle.color.g;
  50852. this._vertexData[offset + 5] = particle.color.b;
  50853. this._vertexData[offset + 6] = particle.color.a;
  50854. this._vertexData[offset + 7] = particle.angle;
  50855. this._vertexData[offset + 8] = particle.size;
  50856. this._vertexData[offset + 9] = offsetX;
  50857. this._vertexData[offset + 10] = offsetY;
  50858. this._vertexData[offset + 11] = particle.cellIndex;
  50859. };
  50860. ParticleSystem.prototype._update = function (newParticles) {
  50861. // Update current
  50862. this._alive = this._particles.length > 0;
  50863. this.updateFunction(this._particles);
  50864. // Add new ones
  50865. var worldMatrix;
  50866. if (this.emitter.position) {
  50867. var emitterMesh = this.emitter;
  50868. worldMatrix = emitterMesh.getWorldMatrix();
  50869. }
  50870. else {
  50871. var emitterPosition = this.emitter;
  50872. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50873. }
  50874. var particle;
  50875. for (var index = 0; index < newParticles; index++) {
  50876. if (this._particles.length === this._capacity) {
  50877. break;
  50878. }
  50879. if (this._stockParticles.length !== 0) {
  50880. particle = this._stockParticles.pop();
  50881. particle.age = 0;
  50882. particle.cellIndex = this.startSpriteCellID;
  50883. }
  50884. else {
  50885. particle = new BABYLON.Particle(this);
  50886. }
  50887. this._particles.push(particle);
  50888. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50889. if (this.startPositionFunction) {
  50890. this.startPositionFunction(worldMatrix, particle.position, particle);
  50891. }
  50892. else {
  50893. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50894. }
  50895. if (this.startDirectionFunction) {
  50896. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50897. }
  50898. else {
  50899. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50900. }
  50901. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50902. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50903. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50904. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50905. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50906. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50907. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50908. }
  50909. };
  50910. ParticleSystem.prototype._getEffect = function () {
  50911. if (this._customEffect) {
  50912. return this._customEffect;
  50913. }
  50914. ;
  50915. var defines = [];
  50916. if (this._scene.clipPlane) {
  50917. defines.push("#define CLIPPLANE");
  50918. }
  50919. if (this._isAnimationSheetEnabled) {
  50920. defines.push("#define ANIMATESHEET");
  50921. }
  50922. // Effect
  50923. var join = defines.join("\n");
  50924. if (this._cachedDefines !== join) {
  50925. this._cachedDefines = join;
  50926. var attributesNamesOrOptions;
  50927. var effectCreationOption;
  50928. if (this._isAnimationSheetEnabled) {
  50929. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50930. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50931. }
  50932. else {
  50933. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50934. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50935. }
  50936. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50937. }
  50938. return this._effect;
  50939. };
  50940. /**
  50941. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50942. */
  50943. ParticleSystem.prototype.animate = function () {
  50944. if (!this._started)
  50945. return;
  50946. var effect = this._getEffect();
  50947. // Check
  50948. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50949. return;
  50950. if (this._currentRenderId === this._scene.getRenderId()) {
  50951. return;
  50952. }
  50953. this._currentRenderId = this._scene.getRenderId();
  50954. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50955. // determine the number of particles we need to create
  50956. var newParticles;
  50957. if (this.manualEmitCount > -1) {
  50958. newParticles = this.manualEmitCount;
  50959. this._newPartsExcess = 0;
  50960. this.manualEmitCount = 0;
  50961. }
  50962. else {
  50963. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50964. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50965. }
  50966. if (this._newPartsExcess > 1.0) {
  50967. newParticles += this._newPartsExcess >> 0;
  50968. this._newPartsExcess -= this._newPartsExcess >> 0;
  50969. }
  50970. this._alive = false;
  50971. if (!this._stopped) {
  50972. this._actualFrame += this._scaledUpdateSpeed;
  50973. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50974. this.stop();
  50975. }
  50976. else {
  50977. newParticles = 0;
  50978. }
  50979. this._update(newParticles);
  50980. // Stopped?
  50981. if (this._stopped) {
  50982. if (!this._alive) {
  50983. this._started = false;
  50984. if (this.onAnimationEnd) {
  50985. this.onAnimationEnd();
  50986. }
  50987. if (this.disposeOnStop) {
  50988. this._scene._toBeDisposed.push(this);
  50989. }
  50990. }
  50991. }
  50992. // Animation sheet
  50993. if (this._isAnimationSheetEnabled) {
  50994. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50995. }
  50996. else {
  50997. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50998. }
  50999. // Update VBO
  51000. var offset = 0;
  51001. for (var index = 0; index < this._particles.length; index++) {
  51002. var particle = this._particles[index];
  51003. this._appendParticleVertexes(offset, particle);
  51004. offset += 4;
  51005. }
  51006. if (this._vertexBuffer) {
  51007. this._vertexBuffer.update(this._vertexData);
  51008. }
  51009. };
  51010. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51011. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51012. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51013. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51014. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51015. };
  51016. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51017. this._appendParticleVertex(offset++, particle, 0, 0);
  51018. this._appendParticleVertex(offset++, particle, 1, 0);
  51019. this._appendParticleVertex(offset++, particle, 1, 1);
  51020. this._appendParticleVertex(offset++, particle, 0, 1);
  51021. };
  51022. /**
  51023. * Rebuilds the particle system.
  51024. */
  51025. ParticleSystem.prototype.rebuild = function () {
  51026. this._createIndexBuffer();
  51027. if (this._vertexBuffer) {
  51028. this._vertexBuffer._rebuild();
  51029. }
  51030. };
  51031. /**
  51032. * Renders the particle system in its current state.
  51033. * @returns the current number of particles
  51034. */
  51035. ParticleSystem.prototype.render = function () {
  51036. var effect = this._getEffect();
  51037. // Check
  51038. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51039. return 0;
  51040. }
  51041. var engine = this._scene.getEngine();
  51042. // Render
  51043. engine.enableEffect(effect);
  51044. engine.setState(false);
  51045. var viewMatrix = this._scene.getViewMatrix();
  51046. effect.setTexture("diffuseSampler", this.particleTexture);
  51047. effect.setMatrix("view", viewMatrix);
  51048. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51049. if (this._isAnimationSheetEnabled) {
  51050. var baseSize = this.particleTexture.getBaseSize();
  51051. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51052. }
  51053. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51054. if (this._scene.clipPlane) {
  51055. var clipPlane = this._scene.clipPlane;
  51056. var invView = viewMatrix.clone();
  51057. invView.invert();
  51058. effect.setMatrix("invView", invView);
  51059. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51060. }
  51061. // VBOs
  51062. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51063. // Draw order
  51064. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51065. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51066. }
  51067. else {
  51068. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51069. }
  51070. if (this.forceDepthWrite) {
  51071. engine.setDepthWrite(true);
  51072. }
  51073. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51075. return this._particles.length;
  51076. };
  51077. /**
  51078. * Disposes the particle system and free the associated resources
  51079. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51080. */
  51081. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51082. if (disposeTexture === void 0) { disposeTexture = true; }
  51083. if (this._vertexBuffer) {
  51084. this._vertexBuffer.dispose();
  51085. this._vertexBuffer = null;
  51086. }
  51087. if (this._indexBuffer) {
  51088. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51089. this._indexBuffer = null;
  51090. }
  51091. if (disposeTexture && this.particleTexture) {
  51092. this.particleTexture.dispose();
  51093. this.particleTexture = null;
  51094. }
  51095. // Remove from scene
  51096. var index = this._scene.particleSystems.indexOf(this);
  51097. if (index > -1) {
  51098. this._scene.particleSystems.splice(index, 1);
  51099. }
  51100. // Callback
  51101. this.onDisposeObservable.notifyObservers(this);
  51102. this.onDisposeObservable.clear();
  51103. };
  51104. /**
  51105. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51106. * @param radius The radius of the sphere to emit from
  51107. * @returns the emitter
  51108. */
  51109. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51110. if (radius === void 0) { radius = 1; }
  51111. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51112. this.particleEmitterType = particleEmitter;
  51113. return particleEmitter;
  51114. };
  51115. /**
  51116. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51117. * @param radius The radius of the sphere to emit from
  51118. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51119. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51120. * @returns the emitter
  51121. */
  51122. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51123. if (radius === void 0) { radius = 1; }
  51124. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51125. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51126. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51127. this.particleEmitterType = particleEmitter;
  51128. return particleEmitter;
  51129. };
  51130. /**
  51131. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51132. * @param radius The radius of the cone to emit from
  51133. * @param angle The base angle of the cone
  51134. * @returns the emitter
  51135. */
  51136. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51137. if (radius === void 0) { radius = 1; }
  51138. if (angle === void 0) { angle = Math.PI / 4; }
  51139. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51140. this.particleEmitterType = particleEmitter;
  51141. return particleEmitter;
  51142. };
  51143. // 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.
  51144. /**
  51145. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51146. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51147. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51148. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51149. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51150. * @returns the emitter
  51151. */
  51152. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51153. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51154. this.direction1 = direction1;
  51155. this.direction2 = direction2;
  51156. this.minEmitBox = minEmitBox;
  51157. this.maxEmitBox = maxEmitBox;
  51158. this.particleEmitterType = particleEmitter;
  51159. return particleEmitter;
  51160. };
  51161. /**
  51162. * Clones the particle system.
  51163. * @param name The name of the cloned object
  51164. * @param newEmitter The new emitter to use
  51165. * @returns the cloned particle system
  51166. */
  51167. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51168. var custom = null;
  51169. var program = null;
  51170. if (this.customShader != null) {
  51171. program = this.customShader;
  51172. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51173. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51174. }
  51175. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51176. result.customShader = program;
  51177. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51178. if (newEmitter === undefined) {
  51179. newEmitter = this.emitter;
  51180. }
  51181. result.emitter = newEmitter;
  51182. if (this.particleTexture) {
  51183. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51184. }
  51185. if (!this.preventAutoStart) {
  51186. result.start();
  51187. }
  51188. return result;
  51189. };
  51190. /**
  51191. * Serializes the particle system to a JSON object.
  51192. * @returns the JSON object
  51193. */
  51194. ParticleSystem.prototype.serialize = function () {
  51195. var serializationObject = {};
  51196. serializationObject.name = this.name;
  51197. serializationObject.id = this.id;
  51198. // Emitter
  51199. if (this.emitter.position) {
  51200. var emitterMesh = this.emitter;
  51201. serializationObject.emitterId = emitterMesh.id;
  51202. }
  51203. else {
  51204. var emitterPosition = this.emitter;
  51205. serializationObject.emitter = emitterPosition.asArray();
  51206. }
  51207. serializationObject.capacity = this.getCapacity();
  51208. if (this.particleTexture) {
  51209. serializationObject.textureName = this.particleTexture.name;
  51210. }
  51211. // Animations
  51212. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51213. // Particle system
  51214. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51215. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51216. serializationObject.minSize = this.minSize;
  51217. serializationObject.maxSize = this.maxSize;
  51218. serializationObject.minEmitPower = this.minEmitPower;
  51219. serializationObject.maxEmitPower = this.maxEmitPower;
  51220. serializationObject.minLifeTime = this.minLifeTime;
  51221. serializationObject.maxLifeTime = this.maxLifeTime;
  51222. serializationObject.emitRate = this.emitRate;
  51223. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51224. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51225. serializationObject.gravity = this.gravity.asArray();
  51226. serializationObject.direction1 = this.direction1.asArray();
  51227. serializationObject.direction2 = this.direction2.asArray();
  51228. serializationObject.color1 = this.color1.asArray();
  51229. serializationObject.color2 = this.color2.asArray();
  51230. serializationObject.colorDead = this.colorDead.asArray();
  51231. serializationObject.updateSpeed = this.updateSpeed;
  51232. serializationObject.targetStopDuration = this.targetStopDuration;
  51233. serializationObject.textureMask = this.textureMask.asArray();
  51234. serializationObject.blendMode = this.blendMode;
  51235. serializationObject.customShader = this.customShader;
  51236. serializationObject.preventAutoStart = this.preventAutoStart;
  51237. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51238. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51239. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51240. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51241. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51242. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51243. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51244. // Emitter
  51245. if (this.particleEmitterType) {
  51246. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51247. }
  51248. return serializationObject;
  51249. };
  51250. /**
  51251. * Parses a JSON object to create a particle system.
  51252. * @param parsedParticleSystem The JSON object to parse
  51253. * @param scene The scene to create the particle system in
  51254. * @param rootUrl The root url to use to load external dependencies like texture
  51255. * @returns the Parsed particle system
  51256. */
  51257. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51258. var name = parsedParticleSystem.name;
  51259. var custom = null;
  51260. var program = null;
  51261. if (parsedParticleSystem.customShader) {
  51262. program = parsedParticleSystem.customShader;
  51263. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51264. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51265. }
  51266. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51267. particleSystem.customShader = program;
  51268. if (parsedParticleSystem.id) {
  51269. particleSystem.id = parsedParticleSystem.id;
  51270. }
  51271. // Auto start
  51272. if (parsedParticleSystem.preventAutoStart) {
  51273. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51274. }
  51275. // Texture
  51276. if (parsedParticleSystem.textureName) {
  51277. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51278. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51279. }
  51280. // Emitter
  51281. if (parsedParticleSystem.emitterId) {
  51282. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51283. }
  51284. else {
  51285. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51286. }
  51287. // Animations
  51288. if (parsedParticleSystem.animations) {
  51289. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51290. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51291. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51292. }
  51293. }
  51294. if (parsedParticleSystem.autoAnimate) {
  51295. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51296. }
  51297. // Particle system
  51298. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51299. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51300. particleSystem.minSize = parsedParticleSystem.minSize;
  51301. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51302. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51303. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51304. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51305. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51306. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51307. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51308. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51309. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51310. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51311. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51312. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51313. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51314. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51315. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51316. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51317. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51318. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51319. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51320. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51321. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51322. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51323. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51324. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51325. if (!particleSystem.preventAutoStart) {
  51326. particleSystem.start();
  51327. }
  51328. return particleSystem;
  51329. };
  51330. /**
  51331. * Source color is added to the destination color without alpha affecting the result.
  51332. */
  51333. ParticleSystem.BLENDMODE_ONEONE = 0;
  51334. /**
  51335. * Blend current color and particle color using particle’s alpha.
  51336. */
  51337. ParticleSystem.BLENDMODE_STANDARD = 1;
  51338. return ParticleSystem;
  51339. }());
  51340. BABYLON.ParticleSystem = ParticleSystem;
  51341. })(BABYLON || (BABYLON = {}));
  51342. //# sourceMappingURL=babylon.particleSystem.js.map
  51343. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51344. var BABYLON;
  51345. (function (BABYLON) {
  51346. /**
  51347. * Particle emitter emitting particles from the inside of a box.
  51348. * It emits the particles randomly between 2 given directions.
  51349. */
  51350. var BoxParticleEmitter = /** @class */ (function () {
  51351. /**
  51352. * Creates a new instance of @see BoxParticleEmitter
  51353. */
  51354. function BoxParticleEmitter() {
  51355. /**
  51356. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51357. */
  51358. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51359. /**
  51360. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51361. */
  51362. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51363. /**
  51364. * 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.
  51365. */
  51366. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51367. /**
  51368. * 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.
  51369. */
  51370. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51371. }
  51372. /**
  51373. * Called by the particle System when the direction is computed for the created particle.
  51374. * @param emitPower is the power of the particle (speed)
  51375. * @param worldMatrix is the world matrix of the particle system
  51376. * @param directionToUpdate is the direction vector to update with the result
  51377. * @param particle is the particle we are computed the direction for
  51378. */
  51379. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51380. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51381. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51382. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51383. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51384. };
  51385. /**
  51386. * Called by the particle System when the position is computed for the created particle.
  51387. * @param worldMatrix is the world matrix of the particle system
  51388. * @param positionToUpdate is the position vector to update with the result
  51389. * @param particle is the particle we are computed the position for
  51390. */
  51391. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51392. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51393. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51394. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51395. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51396. };
  51397. /**
  51398. * Clones the current emitter and returns a copy of it
  51399. * @returns the new emitter
  51400. */
  51401. BoxParticleEmitter.prototype.clone = function () {
  51402. var newOne = new BoxParticleEmitter();
  51403. BABYLON.Tools.DeepCopy(this, newOne);
  51404. return newOne;
  51405. };
  51406. /**
  51407. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51408. * @param effect defines the update shader
  51409. */
  51410. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51411. effect.setVector3("direction1", this.direction1);
  51412. effect.setVector3("direction2", this.direction2);
  51413. effect.setVector3("minEmitBox", this.minEmitBox);
  51414. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51415. };
  51416. /**
  51417. * Returns a string to use to update the GPU particles update shader
  51418. * @returns a string containng the defines string
  51419. */
  51420. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51421. return "#define BOXEMITTER";
  51422. };
  51423. /**
  51424. * Returns the string "BoxEmitter"
  51425. * @returns a string containing the class name
  51426. */
  51427. BoxParticleEmitter.prototype.getClassName = function () {
  51428. return "BoxEmitter";
  51429. };
  51430. /**
  51431. * Serializes the particle system to a JSON object.
  51432. * @returns the JSON object
  51433. */
  51434. BoxParticleEmitter.prototype.serialize = function () {
  51435. var serializationObject = {};
  51436. serializationObject.type = this.getClassName();
  51437. serializationObject.direction1 = this.direction1.asArray();
  51438. ;
  51439. serializationObject.direction2 = this.direction2.asArray();
  51440. ;
  51441. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51442. ;
  51443. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51444. ;
  51445. return serializationObject;
  51446. };
  51447. /**
  51448. * Parse properties from a JSON object
  51449. * @param serializationObject defines the JSON object
  51450. */
  51451. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51452. this.direction1.copyFrom(serializationObject.direction1);
  51453. this.direction2.copyFrom(serializationObject.direction2);
  51454. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51455. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51456. };
  51457. return BoxParticleEmitter;
  51458. }());
  51459. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51460. })(BABYLON || (BABYLON = {}));
  51461. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51462. var BABYLON;
  51463. (function (BABYLON) {
  51464. /**
  51465. * Particle emitter emitting particles from the inside of a cone.
  51466. * It emits the particles alongside the cone volume from the base to the particle.
  51467. * The emission direction might be randomized.
  51468. */
  51469. var ConeParticleEmitter = /** @class */ (function () {
  51470. /**
  51471. * Creates a new instance of @see ConeParticleEmitter
  51472. * @param radius the radius of the emission cone (1 by default)
  51473. * @param angles the cone base angle (PI by default)
  51474. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51475. */
  51476. function ConeParticleEmitter(radius,
  51477. /**
  51478. * The radius of the emission cone.
  51479. */
  51480. angle,
  51481. /**
  51482. * The cone base angle.
  51483. */
  51484. directionRandomizer) {
  51485. if (radius === void 0) { radius = 1; }
  51486. if (angle === void 0) { angle = Math.PI; }
  51487. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51488. this.angle = angle;
  51489. this.directionRandomizer = directionRandomizer;
  51490. this.radius = radius;
  51491. }
  51492. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51493. /**
  51494. * Gets the radius of the emission cone.
  51495. */
  51496. get: function () {
  51497. return this._radius;
  51498. },
  51499. /**
  51500. * Sets the radius of the emission cone.
  51501. */
  51502. set: function (value) {
  51503. this._radius = value;
  51504. if (this.angle !== 0) {
  51505. this._height = value / Math.tan(this.angle / 2);
  51506. }
  51507. else {
  51508. this._height = 1;
  51509. }
  51510. },
  51511. enumerable: true,
  51512. configurable: true
  51513. });
  51514. /**
  51515. * Called by the particle System when the direction is computed for the created particle.
  51516. * @param emitPower is the power of the particle (speed)
  51517. * @param worldMatrix is the world matrix of the particle system
  51518. * @param directionToUpdate is the direction vector to update with the result
  51519. * @param particle is the particle we are computed the direction for
  51520. */
  51521. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51522. if (this.angle === 0) {
  51523. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51524. }
  51525. else {
  51526. // measure the direction Vector from the emitter to the particle.
  51527. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51528. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51529. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51530. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51531. direction.x += randX;
  51532. direction.y += randY;
  51533. direction.z += randZ;
  51534. direction.normalize();
  51535. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51536. }
  51537. };
  51538. /**
  51539. * Called by the particle System when the position is computed for the created particle.
  51540. * @param worldMatrix is the world matrix of the particle system
  51541. * @param positionToUpdate is the position vector to update with the result
  51542. * @param particle is the particle we are computed the position for
  51543. */
  51544. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51545. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51546. var h = BABYLON.Scalar.RandomRange(0, 1);
  51547. // Better distribution in a cone at normal angles.
  51548. h = 1 - h * h;
  51549. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51550. radius = radius * h / this._height;
  51551. var randX = radius * Math.sin(s);
  51552. var randZ = radius * Math.cos(s);
  51553. var randY = h * this._height;
  51554. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51555. };
  51556. /**
  51557. * Clones the current emitter and returns a copy of it
  51558. * @returns the new emitter
  51559. */
  51560. ConeParticleEmitter.prototype.clone = function () {
  51561. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51562. BABYLON.Tools.DeepCopy(this, newOne);
  51563. return newOne;
  51564. };
  51565. /**
  51566. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51567. * @param effect defines the update shader
  51568. */
  51569. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51570. effect.setFloat("radius", this.radius);
  51571. effect.setFloat("angle", this.angle);
  51572. effect.setFloat("height", this._height);
  51573. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51574. };
  51575. /**
  51576. * Returns a string to use to update the GPU particles update shader
  51577. * @returns a string containng the defines string
  51578. */
  51579. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51580. return "#define CONEEMITTER";
  51581. };
  51582. /**
  51583. * Returns the string "BoxEmitter"
  51584. * @returns a string containing the class name
  51585. */
  51586. ConeParticleEmitter.prototype.getClassName = function () {
  51587. return "ConeEmitter";
  51588. };
  51589. /**
  51590. * Serializes the particle system to a JSON object.
  51591. * @returns the JSON object
  51592. */
  51593. ConeParticleEmitter.prototype.serialize = function () {
  51594. var serializationObject = {};
  51595. serializationObject.type = this.getClassName();
  51596. serializationObject.radius = this.radius;
  51597. serializationObject.angle = this.angle;
  51598. serializationObject.directionRandomizer = this.directionRandomizer;
  51599. return serializationObject;
  51600. };
  51601. /**
  51602. * Parse properties from a JSON object
  51603. * @param serializationObject defines the JSON object
  51604. */
  51605. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51606. this.radius = serializationObject.radius;
  51607. this.angle = serializationObject.angle;
  51608. this.directionRandomizer = serializationObject.directionRandomizer;
  51609. };
  51610. return ConeParticleEmitter;
  51611. }());
  51612. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51613. })(BABYLON || (BABYLON = {}));
  51614. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51615. var BABYLON;
  51616. (function (BABYLON) {
  51617. /**
  51618. * Particle emitter emitting particles from the inside of a sphere.
  51619. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51620. */
  51621. var SphereParticleEmitter = /** @class */ (function () {
  51622. /**
  51623. * Creates a new instance of @see SphereParticleEmitter
  51624. * @param radius the radius of the emission sphere (1 by default)
  51625. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51626. */
  51627. function SphereParticleEmitter(
  51628. /**
  51629. * The radius of the emission sphere.
  51630. */
  51631. radius,
  51632. /**
  51633. * How much to randomize the particle direction [0-1].
  51634. */
  51635. directionRandomizer) {
  51636. if (radius === void 0) { radius = 1; }
  51637. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51638. this.radius = radius;
  51639. this.directionRandomizer = directionRandomizer;
  51640. }
  51641. /**
  51642. * Called by the particle System when the direction is computed for the created particle.
  51643. * @param emitPower is the power of the particle (speed)
  51644. * @param worldMatrix is the world matrix of the particle system
  51645. * @param directionToUpdate is the direction vector to update with the result
  51646. * @param particle is the particle we are computed the direction for
  51647. */
  51648. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51649. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51650. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51651. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51652. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51653. direction.x += randX;
  51654. direction.y += randY;
  51655. direction.z += randZ;
  51656. direction.normalize();
  51657. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51658. };
  51659. /**
  51660. * Called by the particle System when the position is computed for the created particle.
  51661. * @param worldMatrix is the world matrix of the particle system
  51662. * @param positionToUpdate is the position vector to update with the result
  51663. * @param particle is the particle we are computed the position for
  51664. */
  51665. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51666. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51667. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51668. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51669. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51670. var randY = randRadius * Math.cos(theta);
  51671. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51672. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51673. };
  51674. /**
  51675. * Clones the current emitter and returns a copy of it
  51676. * @returns the new emitter
  51677. */
  51678. SphereParticleEmitter.prototype.clone = function () {
  51679. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51680. BABYLON.Tools.DeepCopy(this, newOne);
  51681. return newOne;
  51682. };
  51683. /**
  51684. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51685. * @param effect defines the update shader
  51686. */
  51687. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51688. effect.setFloat("radius", this.radius);
  51689. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51690. };
  51691. /**
  51692. * Returns a string to use to update the GPU particles update shader
  51693. * @returns a string containng the defines string
  51694. */
  51695. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51696. return "#define SPHEREEMITTER";
  51697. };
  51698. /**
  51699. * Returns the string "SphereParticleEmitter"
  51700. * @returns a string containing the class name
  51701. */
  51702. SphereParticleEmitter.prototype.getClassName = function () {
  51703. return "SphereParticleEmitter";
  51704. };
  51705. /**
  51706. * Serializes the particle system to a JSON object.
  51707. * @returns the JSON object
  51708. */
  51709. SphereParticleEmitter.prototype.serialize = function () {
  51710. var serializationObject = {};
  51711. serializationObject.type = this.getClassName();
  51712. serializationObject.radius = this.radius;
  51713. serializationObject.directionRandomizer = this.directionRandomizer;
  51714. return serializationObject;
  51715. };
  51716. /**
  51717. * Parse properties from a JSON object
  51718. * @param serializationObject defines the JSON object
  51719. */
  51720. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51721. this.radius = serializationObject.radius;
  51722. this.directionRandomizer = serializationObject.directionRandomizer;
  51723. };
  51724. return SphereParticleEmitter;
  51725. }());
  51726. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51727. /**
  51728. * Particle emitter emitting particles from the inside of a sphere.
  51729. * It emits the particles randomly between two vectors.
  51730. */
  51731. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51732. __extends(SphereDirectedParticleEmitter, _super);
  51733. /**
  51734. * Creates a new instance of @see SphereDirectedParticleEmitter
  51735. * @param radius the radius of the emission sphere (1 by default)
  51736. * @param direction1 the min limit of the emission direction (up vector by default)
  51737. * @param direction2 the max limit of the emission direction (up vector by default)
  51738. */
  51739. function SphereDirectedParticleEmitter(radius,
  51740. /**
  51741. * The min limit of the emission direction.
  51742. */
  51743. direction1,
  51744. /**
  51745. * The max limit of the emission direction.
  51746. */
  51747. direction2) {
  51748. if (radius === void 0) { radius = 1; }
  51749. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51750. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51751. var _this = _super.call(this, radius) || this;
  51752. _this.direction1 = direction1;
  51753. _this.direction2 = direction2;
  51754. return _this;
  51755. }
  51756. /**
  51757. * Called by the particle System when the direction is computed for the created particle.
  51758. * @param emitPower is the power of the particle (speed)
  51759. * @param worldMatrix is the world matrix of the particle system
  51760. * @param directionToUpdate is the direction vector to update with the result
  51761. * @param particle is the particle we are computed the direction for
  51762. */
  51763. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51764. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51765. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51766. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51767. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51768. };
  51769. /**
  51770. * Clones the current emitter and returns a copy of it
  51771. * @returns the new emitter
  51772. */
  51773. SphereDirectedParticleEmitter.prototype.clone = function () {
  51774. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51775. BABYLON.Tools.DeepCopy(this, newOne);
  51776. return newOne;
  51777. };
  51778. /**
  51779. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51780. * @param effect defines the update shader
  51781. */
  51782. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51783. effect.setFloat("radius", this.radius);
  51784. effect.setVector3("direction1", this.direction1);
  51785. effect.setVector3("direction2", this.direction2);
  51786. };
  51787. /**
  51788. * Returns a string to use to update the GPU particles update shader
  51789. * @returns a string containng the defines string
  51790. */
  51791. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51792. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51793. };
  51794. /**
  51795. * Returns the string "SphereDirectedParticleEmitter"
  51796. * @returns a string containing the class name
  51797. */
  51798. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51799. return "SphereDirectedParticleEmitter";
  51800. };
  51801. /**
  51802. * Serializes the particle system to a JSON object.
  51803. * @returns the JSON object
  51804. */
  51805. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51806. var serializationObject = _super.prototype.serialize.call(this);
  51807. ;
  51808. serializationObject.direction1 = this.direction1.asArray();
  51809. ;
  51810. serializationObject.direction2 = this.direction2.asArray();
  51811. ;
  51812. return serializationObject;
  51813. };
  51814. /**
  51815. * Parse properties from a JSON object
  51816. * @param serializationObject defines the JSON object
  51817. */
  51818. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51819. _super.prototype.parse.call(this, serializationObject);
  51820. this.direction1.copyFrom(serializationObject.direction1);
  51821. this.direction2.copyFrom(serializationObject.direction2);
  51822. };
  51823. return SphereDirectedParticleEmitter;
  51824. }(SphereParticleEmitter));
  51825. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51826. })(BABYLON || (BABYLON = {}));
  51827. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51828. var BABYLON;
  51829. (function (BABYLON) {
  51830. /**
  51831. * Represents one particle of a solid particle system.
  51832. * @see SolidParticleSystem
  51833. */
  51834. var SolidParticle = /** @class */ (function () {
  51835. /**
  51836. * Creates a Solid Particle object.
  51837. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51838. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51839. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51840. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51841. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51842. * @param shapeId (integer) is the model shape identifier in the SPS.
  51843. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51844. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51845. */
  51846. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51847. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51848. /**
  51849. * particle global index
  51850. */
  51851. this.idx = 0;
  51852. /**
  51853. * The color of the particle
  51854. */
  51855. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51856. /**
  51857. * The world space position of the particle.
  51858. */
  51859. this.position = BABYLON.Vector3.Zero();
  51860. /**
  51861. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51862. */
  51863. this.rotation = BABYLON.Vector3.Zero();
  51864. /**
  51865. * The scaling of the particle.
  51866. */
  51867. this.scaling = BABYLON.Vector3.One();
  51868. /**
  51869. * The uvs of the particle.
  51870. */
  51871. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51872. /**
  51873. * The current speed of the particle.
  51874. */
  51875. this.velocity = BABYLON.Vector3.Zero();
  51876. /**
  51877. * The pivot point in the particle local space.
  51878. */
  51879. this.pivot = BABYLON.Vector3.Zero();
  51880. /**
  51881. * Must the particle be translated from its pivot point in its local space ?
  51882. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51883. * Default : false
  51884. */
  51885. this.translateFromPivot = false;
  51886. /**
  51887. * Is the particle active or not ?
  51888. */
  51889. this.alive = true;
  51890. /**
  51891. * Is the particle visible or not ?
  51892. */
  51893. this.isVisible = true;
  51894. /**
  51895. * Index of this particle in the global "positions" array (Internal use)
  51896. */
  51897. this._pos = 0;
  51898. /**
  51899. * Index of this particle in the global "indices" array (Internal use)
  51900. */
  51901. this._ind = 0;
  51902. /**
  51903. * ModelShape id of this particle
  51904. */
  51905. this.shapeId = 0;
  51906. /**
  51907. * Index of the particle in its shape id (Internal use)
  51908. */
  51909. this.idxInShape = 0;
  51910. /**
  51911. * Still set as invisible in order to skip useless computations (Internal use)
  51912. */
  51913. this._stillInvisible = false;
  51914. /**
  51915. * Last computed particle rotation matrix
  51916. */
  51917. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51918. /**
  51919. * Parent particle Id, if any.
  51920. * Default null.
  51921. */
  51922. this.parentId = null;
  51923. /**
  51924. * Internal global position in the SPS.
  51925. */
  51926. this._globalPosition = BABYLON.Vector3.Zero();
  51927. this.idx = particleIndex;
  51928. this._pos = positionIndex;
  51929. this._ind = indiceIndex;
  51930. this._model = model;
  51931. this.shapeId = shapeId;
  51932. this.idxInShape = idxInShape;
  51933. this._sps = sps;
  51934. if (modelBoundingInfo) {
  51935. this._modelBoundingInfo = modelBoundingInfo;
  51936. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51937. }
  51938. }
  51939. Object.defineProperty(SolidParticle.prototype, "scale", {
  51940. /**
  51941. * Legacy support, changed scale to scaling
  51942. */
  51943. get: function () {
  51944. return this.scaling;
  51945. },
  51946. /**
  51947. * Legacy support, changed scale to scaling
  51948. */
  51949. set: function (scale) {
  51950. this.scaling = scale;
  51951. },
  51952. enumerable: true,
  51953. configurable: true
  51954. });
  51955. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51956. /**
  51957. * Legacy support, changed quaternion to rotationQuaternion
  51958. */
  51959. get: function () {
  51960. return this.rotationQuaternion;
  51961. },
  51962. /**
  51963. * Legacy support, changed quaternion to rotationQuaternion
  51964. */
  51965. set: function (q) {
  51966. this.rotationQuaternion = q;
  51967. },
  51968. enumerable: true,
  51969. configurable: true
  51970. });
  51971. /**
  51972. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51973. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51974. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51975. * @returns true if it intersects
  51976. */
  51977. SolidParticle.prototype.intersectsMesh = function (target) {
  51978. if (!this._boundingInfo || !target._boundingInfo) {
  51979. return false;
  51980. }
  51981. if (this._sps._bSphereOnly) {
  51982. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51983. }
  51984. return this._boundingInfo.intersects(target._boundingInfo, false);
  51985. };
  51986. return SolidParticle;
  51987. }());
  51988. BABYLON.SolidParticle = SolidParticle;
  51989. /**
  51990. * Represents the shape of the model used by one particle of a solid particle system.
  51991. * SPS internal tool, don't use it manually.
  51992. * @see SolidParticleSystem
  51993. */
  51994. var ModelShape = /** @class */ (function () {
  51995. /**
  51996. * 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.
  51997. * SPS internal tool, don't use it manually.
  51998. * @ignore
  51999. */
  52000. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52001. /**
  52002. * length of the shape in the model indices array (internal use)
  52003. */
  52004. this._indicesLength = 0;
  52005. this.shapeID = id;
  52006. this._shape = shape;
  52007. this._indicesLength = indicesLength;
  52008. this._shapeUV = shapeUV;
  52009. this._positionFunction = posFunction;
  52010. this._vertexFunction = vtxFunction;
  52011. }
  52012. return ModelShape;
  52013. }());
  52014. BABYLON.ModelShape = ModelShape;
  52015. /**
  52016. * Represents a Depth Sorted Particle in the solid particle system.
  52017. * @see SolidParticleSystem
  52018. */
  52019. var DepthSortedParticle = /** @class */ (function () {
  52020. function DepthSortedParticle() {
  52021. /**
  52022. * Index of the particle in the "indices" array
  52023. */
  52024. this.ind = 0;
  52025. /**
  52026. * Length of the particle shape in the "indices" array
  52027. */
  52028. this.indicesLength = 0;
  52029. /**
  52030. * Squared distance from the particle to the camera
  52031. */
  52032. this.sqDistance = 0.0;
  52033. }
  52034. return DepthSortedParticle;
  52035. }());
  52036. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52037. })(BABYLON || (BABYLON = {}));
  52038. //# sourceMappingURL=babylon.solidParticle.js.map
  52039. var BABYLON;
  52040. (function (BABYLON) {
  52041. /**
  52042. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52043. *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.
  52044. * The SPS is also a particle system. It provides some methods to manage the particles.
  52045. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52046. *
  52047. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52048. */
  52049. var SolidParticleSystem = /** @class */ (function () {
  52050. /**
  52051. * Creates a SPS (Solid Particle System) object.
  52052. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52053. * @param scene (Scene) is the scene in which the SPS is added.
  52054. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52055. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52056. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52057. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52058. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52059. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52060. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52061. */
  52062. function SolidParticleSystem(name, scene, options) {
  52063. /**
  52064. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52065. * Example : var p = SPS.particles[i];
  52066. */
  52067. this.particles = new Array();
  52068. /**
  52069. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52070. */
  52071. this.nbParticles = 0;
  52072. /**
  52073. * If the particles must ever face the camera (default false). Useful for planar particles.
  52074. */
  52075. this.billboard = false;
  52076. /**
  52077. * Recompute normals when adding a shape
  52078. */
  52079. this.recomputeNormals = true;
  52080. /**
  52081. * This a counter ofr your own usage. It's not set by any SPS functions.
  52082. */
  52083. this.counter = 0;
  52084. /**
  52085. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52086. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52087. */
  52088. this.vars = {};
  52089. /**
  52090. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52091. */
  52092. this._bSphereOnly = false;
  52093. /**
  52094. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52095. */
  52096. this._bSphereRadiusFactor = 1.0;
  52097. this._positions = new Array();
  52098. this._indices = new Array();
  52099. this._normals = new Array();
  52100. this._colors = new Array();
  52101. this._uvs = new Array();
  52102. this._index = 0; // indices index
  52103. this._updatable = true;
  52104. this._pickable = false;
  52105. this._isVisibilityBoxLocked = false;
  52106. this._alwaysVisible = false;
  52107. this._depthSort = false;
  52108. this._shapeCounter = 0;
  52109. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52110. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52111. this._computeParticleColor = true;
  52112. this._computeParticleTexture = true;
  52113. this._computeParticleRotation = true;
  52114. this._computeParticleVertex = false;
  52115. this._computeBoundingBox = false;
  52116. this._depthSortParticles = true;
  52117. this._cam_axisZ = BABYLON.Vector3.Zero();
  52118. this._cam_axisY = BABYLON.Vector3.Zero();
  52119. this._cam_axisX = BABYLON.Vector3.Zero();
  52120. this._axisZ = BABYLON.Axis.Z;
  52121. this._camDir = BABYLON.Vector3.Zero();
  52122. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52123. this._rotMatrix = new BABYLON.Matrix();
  52124. this._invertMatrix = new BABYLON.Matrix();
  52125. this._rotated = BABYLON.Vector3.Zero();
  52126. this._quaternion = new BABYLON.Quaternion();
  52127. this._vertex = BABYLON.Vector3.Zero();
  52128. this._normal = BABYLON.Vector3.Zero();
  52129. this._yaw = 0.0;
  52130. this._pitch = 0.0;
  52131. this._roll = 0.0;
  52132. this._halfroll = 0.0;
  52133. this._halfpitch = 0.0;
  52134. this._halfyaw = 0.0;
  52135. this._sinRoll = 0.0;
  52136. this._cosRoll = 0.0;
  52137. this._sinPitch = 0.0;
  52138. this._cosPitch = 0.0;
  52139. this._sinYaw = 0.0;
  52140. this._cosYaw = 0.0;
  52141. this._mustUnrotateFixedNormals = false;
  52142. this._minimum = BABYLON.Vector3.Zero();
  52143. this._maximum = BABYLON.Vector3.Zero();
  52144. this._minBbox = BABYLON.Vector3.Zero();
  52145. this._maxBbox = BABYLON.Vector3.Zero();
  52146. this._particlesIntersect = false;
  52147. this._depthSortFunction = function (p1, p2) {
  52148. return (p2.sqDistance - p1.sqDistance);
  52149. };
  52150. this._needs32Bits = false;
  52151. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52152. this._scaledPivot = BABYLON.Vector3.Zero();
  52153. this._particleHasParent = false;
  52154. this.name = name;
  52155. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52156. this._camera = scene.activeCamera;
  52157. this._pickable = options ? options.isPickable : false;
  52158. this._depthSort = options ? options.enableDepthSort : false;
  52159. this._particlesIntersect = options ? options.particleIntersection : false;
  52160. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52161. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52162. if (options && options.updatable) {
  52163. this._updatable = options.updatable;
  52164. }
  52165. else {
  52166. this._updatable = true;
  52167. }
  52168. if (this._pickable) {
  52169. this.pickedParticles = [];
  52170. }
  52171. if (this._depthSort) {
  52172. this.depthSortedParticles = [];
  52173. }
  52174. }
  52175. /**
  52176. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52177. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52178. * @returns the created mesh
  52179. */
  52180. SolidParticleSystem.prototype.buildMesh = function () {
  52181. if (this.nbParticles === 0) {
  52182. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52183. this.addShape(triangle, 1);
  52184. triangle.dispose();
  52185. }
  52186. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52187. this._positions32 = new Float32Array(this._positions);
  52188. this._uvs32 = new Float32Array(this._uvs);
  52189. this._colors32 = new Float32Array(this._colors);
  52190. if (this.recomputeNormals) {
  52191. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52192. }
  52193. this._normals32 = new Float32Array(this._normals);
  52194. this._fixedNormal32 = new Float32Array(this._normals);
  52195. if (this._mustUnrotateFixedNormals) {
  52196. this._unrotateFixedNormals();
  52197. }
  52198. var vertexData = new BABYLON.VertexData();
  52199. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52200. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52201. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52202. if (this._uvs32) {
  52203. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52204. ;
  52205. }
  52206. if (this._colors32) {
  52207. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52208. }
  52209. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52210. vertexData.applyToMesh(mesh, this._updatable);
  52211. this.mesh = mesh;
  52212. this.mesh.isPickable = this._pickable;
  52213. // free memory
  52214. if (!this._depthSort) {
  52215. this._indices = null;
  52216. }
  52217. this._positions = null;
  52218. this._normals = null;
  52219. this._uvs = null;
  52220. this._colors = null;
  52221. if (!this._updatable) {
  52222. this.particles.length = 0;
  52223. }
  52224. return mesh;
  52225. };
  52226. /**
  52227. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52228. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52229. * Thus the particles generated from `digest()` have their property `position` set yet.
  52230. * @param mesh ( Mesh ) is the mesh to be digested
  52231. * @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
  52232. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52233. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52234. * @returns the current SPS
  52235. */
  52236. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52237. var size = (options && options.facetNb) || 1;
  52238. var number = (options && options.number) || 0;
  52239. var delta = (options && options.delta) || 0;
  52240. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52241. var meshInd = mesh.getIndices();
  52242. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52243. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52244. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52245. var f = 0; // facet counter
  52246. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52247. // compute size from number
  52248. if (number) {
  52249. number = (number > totalFacets) ? totalFacets : number;
  52250. size = Math.round(totalFacets / number);
  52251. delta = 0;
  52252. }
  52253. else {
  52254. size = (size > totalFacets) ? totalFacets : size;
  52255. }
  52256. var facetPos = []; // submesh positions
  52257. var facetInd = []; // submesh indices
  52258. var facetUV = []; // submesh UV
  52259. var facetCol = []; // submesh colors
  52260. var barycenter = BABYLON.Vector3.Zero();
  52261. var sizeO = size;
  52262. while (f < totalFacets) {
  52263. size = sizeO + Math.floor((1 + delta) * Math.random());
  52264. if (f > totalFacets - size) {
  52265. size = totalFacets - f;
  52266. }
  52267. // reset temp arrays
  52268. facetPos.length = 0;
  52269. facetInd.length = 0;
  52270. facetUV.length = 0;
  52271. facetCol.length = 0;
  52272. // iterate over "size" facets
  52273. var fi = 0;
  52274. for (var j = f * 3; j < (f + size) * 3; j++) {
  52275. facetInd.push(fi);
  52276. var i = meshInd[j];
  52277. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52278. if (meshUV) {
  52279. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52280. }
  52281. if (meshCol) {
  52282. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52283. }
  52284. fi++;
  52285. }
  52286. // create a model shape for each single particle
  52287. var idx = this.nbParticles;
  52288. var shape = this._posToShape(facetPos);
  52289. var shapeUV = this._uvsToShapeUV(facetUV);
  52290. // compute the barycenter of the shape
  52291. var v;
  52292. for (v = 0; v < shape.length; v++) {
  52293. barycenter.addInPlace(shape[v]);
  52294. }
  52295. barycenter.scaleInPlace(1 / shape.length);
  52296. // shift the shape from its barycenter to the origin
  52297. for (v = 0; v < shape.length; v++) {
  52298. shape[v].subtractInPlace(barycenter);
  52299. }
  52300. var bInfo;
  52301. if (this._particlesIntersect) {
  52302. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52303. }
  52304. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52305. // add the particle in the SPS
  52306. var currentPos = this._positions.length;
  52307. var currentInd = this._indices.length;
  52308. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52309. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52310. // initialize the particle position
  52311. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52312. this._index += shape.length;
  52313. idx++;
  52314. this.nbParticles++;
  52315. this._shapeCounter++;
  52316. f += size;
  52317. }
  52318. return this;
  52319. };
  52320. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52321. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52322. var index = 0;
  52323. var idx = 0;
  52324. for (var p = 0; p < this.particles.length; p++) {
  52325. this._particle = this.particles[p];
  52326. this._shape = this._particle._model._shape;
  52327. if (this._particle.rotationQuaternion) {
  52328. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52329. }
  52330. else {
  52331. this._yaw = this._particle.rotation.y;
  52332. this._pitch = this._particle.rotation.x;
  52333. this._roll = this._particle.rotation.z;
  52334. this._quaternionRotationYPR();
  52335. }
  52336. this._quaternionToRotationMatrix();
  52337. this._rotMatrix.invertToRef(this._invertMatrix);
  52338. for (var pt = 0; pt < this._shape.length; pt++) {
  52339. idx = index + pt * 3;
  52340. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52341. this._fixedNormal32[idx] = this._normal.x;
  52342. this._fixedNormal32[idx + 1] = this._normal.y;
  52343. this._fixedNormal32[idx + 2] = this._normal.z;
  52344. }
  52345. index = idx + 3;
  52346. }
  52347. };
  52348. //reset copy
  52349. SolidParticleSystem.prototype._resetCopy = function () {
  52350. this._copy.position.x = 0;
  52351. this._copy.position.y = 0;
  52352. this._copy.position.z = 0;
  52353. this._copy.rotation.x = 0;
  52354. this._copy.rotation.y = 0;
  52355. this._copy.rotation.z = 0;
  52356. this._copy.rotationQuaternion = null;
  52357. this._copy.scaling.x = 1.0;
  52358. this._copy.scaling.y = 1.0;
  52359. this._copy.scaling.z = 1.0;
  52360. this._copy.uvs.x = 0;
  52361. this._copy.uvs.y = 0;
  52362. this._copy.uvs.z = 1.0;
  52363. this._copy.uvs.w = 1.0;
  52364. this._copy.color = null;
  52365. this._copy.translateFromPivot = false;
  52366. };
  52367. // _meshBuilder : inserts the shape model in the global SPS mesh
  52368. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52369. var i;
  52370. var u = 0;
  52371. var c = 0;
  52372. var n = 0;
  52373. this._resetCopy();
  52374. if (options && options.positionFunction) {
  52375. options.positionFunction(this._copy, idx, idxInShape);
  52376. this._mustUnrotateFixedNormals = true;
  52377. }
  52378. if (this._copy.rotationQuaternion) {
  52379. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52380. }
  52381. else {
  52382. this._yaw = this._copy.rotation.y;
  52383. this._pitch = this._copy.rotation.x;
  52384. this._roll = this._copy.rotation.z;
  52385. this._quaternionRotationYPR();
  52386. }
  52387. this._quaternionToRotationMatrix();
  52388. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52389. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52390. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52391. if (this._copy.translateFromPivot) {
  52392. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52393. }
  52394. else {
  52395. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52396. }
  52397. for (i = 0; i < shape.length; i++) {
  52398. this._vertex.x = shape[i].x;
  52399. this._vertex.y = shape[i].y;
  52400. this._vertex.z = shape[i].z;
  52401. if (options && options.vertexFunction) {
  52402. options.vertexFunction(this._copy, this._vertex, i);
  52403. }
  52404. this._vertex.x *= this._copy.scaling.x;
  52405. this._vertex.y *= this._copy.scaling.y;
  52406. this._vertex.z *= this._copy.scaling.z;
  52407. this._vertex.x -= this._scaledPivot.x;
  52408. this._vertex.y -= this._scaledPivot.y;
  52409. this._vertex.z -= this._scaledPivot.z;
  52410. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52411. this._rotated.addInPlace(this._pivotBackTranslation);
  52412. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52413. if (meshUV) {
  52414. 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);
  52415. u += 2;
  52416. }
  52417. if (this._copy.color) {
  52418. this._color = this._copy.color;
  52419. }
  52420. else if (meshCol && meshCol[c] !== undefined) {
  52421. this._color.r = meshCol[c];
  52422. this._color.g = meshCol[c + 1];
  52423. this._color.b = meshCol[c + 2];
  52424. this._color.a = meshCol[c + 3];
  52425. }
  52426. else {
  52427. this._color.r = 1.0;
  52428. this._color.g = 1.0;
  52429. this._color.b = 1.0;
  52430. this._color.a = 1.0;
  52431. }
  52432. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52433. c += 4;
  52434. if (!this.recomputeNormals && meshNor) {
  52435. this._normal.x = meshNor[n];
  52436. this._normal.y = meshNor[n + 1];
  52437. this._normal.z = meshNor[n + 2];
  52438. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52439. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52440. n += 3;
  52441. }
  52442. }
  52443. for (i = 0; i < meshInd.length; i++) {
  52444. var current_ind = p + meshInd[i];
  52445. indices.push(current_ind);
  52446. if (current_ind > 65535) {
  52447. this._needs32Bits = true;
  52448. }
  52449. }
  52450. if (this._pickable) {
  52451. var nbfaces = meshInd.length / 3;
  52452. for (i = 0; i < nbfaces; i++) {
  52453. this.pickedParticles.push({ idx: idx, faceId: i });
  52454. }
  52455. }
  52456. if (this._depthSort) {
  52457. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52458. }
  52459. return this._copy;
  52460. };
  52461. // returns a shape array from positions array
  52462. SolidParticleSystem.prototype._posToShape = function (positions) {
  52463. var shape = [];
  52464. for (var i = 0; i < positions.length; i += 3) {
  52465. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52466. }
  52467. return shape;
  52468. };
  52469. // returns a shapeUV array from a Vector4 uvs
  52470. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52471. var shapeUV = [];
  52472. if (uvs) {
  52473. for (var i = 0; i < uvs.length; i++)
  52474. shapeUV.push(uvs[i]);
  52475. }
  52476. return shapeUV;
  52477. };
  52478. // adds a new particle object in the particles array
  52479. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52480. if (bInfo === void 0) { bInfo = null; }
  52481. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52482. this.particles.push(sp);
  52483. return sp;
  52484. };
  52485. /**
  52486. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52487. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52488. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52489. * @param nb (positive integer) the number of particles to be created from this model
  52490. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52491. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52492. * @returns the number of shapes in the system
  52493. */
  52494. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52495. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52496. var meshInd = mesh.getIndices();
  52497. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52498. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52499. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52500. var bbInfo;
  52501. if (this._particlesIntersect) {
  52502. bbInfo = mesh.getBoundingInfo();
  52503. }
  52504. var shape = this._posToShape(meshPos);
  52505. var shapeUV = this._uvsToShapeUV(meshUV);
  52506. var posfunc = options ? options.positionFunction : null;
  52507. var vtxfunc = options ? options.vertexFunction : null;
  52508. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52509. // particles
  52510. var sp;
  52511. var currentCopy;
  52512. var idx = this.nbParticles;
  52513. for (var i = 0; i < nb; i++) {
  52514. var currentPos = this._positions.length;
  52515. var currentInd = this._indices.length;
  52516. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52517. if (this._updatable) {
  52518. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52519. sp.position.copyFrom(currentCopy.position);
  52520. sp.rotation.copyFrom(currentCopy.rotation);
  52521. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52522. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52523. }
  52524. if (currentCopy.color && sp.color) {
  52525. sp.color.copyFrom(currentCopy.color);
  52526. }
  52527. sp.scaling.copyFrom(currentCopy.scaling);
  52528. sp.uvs.copyFrom(currentCopy.uvs);
  52529. }
  52530. this._index += shape.length;
  52531. idx++;
  52532. }
  52533. this.nbParticles += nb;
  52534. this._shapeCounter++;
  52535. return this._shapeCounter - 1;
  52536. };
  52537. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52538. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52539. this._resetCopy();
  52540. if (particle._model._positionFunction) {
  52541. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52542. }
  52543. if (this._copy.rotationQuaternion) {
  52544. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52545. }
  52546. else {
  52547. this._yaw = this._copy.rotation.y;
  52548. this._pitch = this._copy.rotation.x;
  52549. this._roll = this._copy.rotation.z;
  52550. this._quaternionRotationYPR();
  52551. }
  52552. this._quaternionToRotationMatrix();
  52553. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52554. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52555. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52556. if (this._copy.translateFromPivot) {
  52557. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52558. }
  52559. else {
  52560. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52561. }
  52562. this._shape = particle._model._shape;
  52563. for (var pt = 0; pt < this._shape.length; pt++) {
  52564. this._vertex.x = this._shape[pt].x;
  52565. this._vertex.y = this._shape[pt].y;
  52566. this._vertex.z = this._shape[pt].z;
  52567. if (particle._model._vertexFunction) {
  52568. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52569. }
  52570. this._vertex.x *= this._copy.scaling.x;
  52571. this._vertex.y *= this._copy.scaling.y;
  52572. this._vertex.z *= this._copy.scaling.z;
  52573. this._vertex.x -= this._scaledPivot.x;
  52574. this._vertex.y -= this._scaledPivot.y;
  52575. this._vertex.z -= this._scaledPivot.z;
  52576. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52577. this._rotated.addInPlace(this._pivotBackTranslation);
  52578. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52579. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52580. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52581. }
  52582. particle.position.x = 0.0;
  52583. particle.position.y = 0.0;
  52584. particle.position.z = 0.0;
  52585. particle.rotation.x = 0.0;
  52586. particle.rotation.y = 0.0;
  52587. particle.rotation.z = 0.0;
  52588. particle.rotationQuaternion = null;
  52589. particle.scaling.x = 1.0;
  52590. particle.scaling.y = 1.0;
  52591. particle.scaling.z = 1.0;
  52592. particle.uvs.x = 0.0;
  52593. particle.uvs.y = 0.0;
  52594. particle.uvs.z = 1.0;
  52595. particle.uvs.w = 1.0;
  52596. particle.pivot.x = 0.0;
  52597. particle.pivot.y = 0.0;
  52598. particle.pivot.z = 0.0;
  52599. particle.translateFromPivot = false;
  52600. particle.parentId = null;
  52601. };
  52602. /**
  52603. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52604. * @returns the SPS.
  52605. */
  52606. SolidParticleSystem.prototype.rebuildMesh = function () {
  52607. for (var p = 0; p < this.particles.length; p++) {
  52608. this._rebuildParticle(this.particles[p]);
  52609. }
  52610. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52611. return this;
  52612. };
  52613. /**
  52614. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52615. * This method calls `updateParticle()` for each particle of the SPS.
  52616. * For an animated SPS, it is usually called within the render loop.
  52617. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52618. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52619. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52620. * @returns the SPS.
  52621. */
  52622. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52623. if (start === void 0) { start = 0; }
  52624. if (end === void 0) { end = this.nbParticles - 1; }
  52625. if (update === void 0) { update = true; }
  52626. if (!this._updatable) {
  52627. return this;
  52628. }
  52629. // custom beforeUpdate
  52630. this.beforeUpdateParticles(start, end, update);
  52631. this._cam_axisX.x = 1.0;
  52632. this._cam_axisX.y = 0.0;
  52633. this._cam_axisX.z = 0.0;
  52634. this._cam_axisY.x = 0.0;
  52635. this._cam_axisY.y = 1.0;
  52636. this._cam_axisY.z = 0.0;
  52637. this._cam_axisZ.x = 0.0;
  52638. this._cam_axisZ.y = 0.0;
  52639. this._cam_axisZ.z = 1.0;
  52640. // cases when the World Matrix is to be computed first
  52641. if (this.billboard || this._depthSort) {
  52642. this.mesh.computeWorldMatrix(true);
  52643. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52644. }
  52645. // if the particles will always face the camera
  52646. if (this.billboard) {
  52647. // compute the camera position and un-rotate it by the current mesh rotation
  52648. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52649. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52650. this._cam_axisZ.normalize();
  52651. // same for camera up vector extracted from the cam view matrix
  52652. var view = this._camera.getViewMatrix(true);
  52653. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52654. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52655. this._cam_axisY.normalize();
  52656. this._cam_axisX.normalize();
  52657. }
  52658. // if depthSort, compute the camera global position in the mesh local system
  52659. if (this._depthSort) {
  52660. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52661. }
  52662. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52663. var idx = 0; // current position index in the global array positions32
  52664. var index = 0; // position start index in the global array positions32 of the current particle
  52665. var colidx = 0; // current color index in the global array colors32
  52666. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52667. var uvidx = 0; // current uv index in the global array uvs32
  52668. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52669. var pt = 0; // current index in the particle model shape
  52670. if (this.mesh.isFacetDataEnabled) {
  52671. this._computeBoundingBox = true;
  52672. }
  52673. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52674. if (this._computeBoundingBox) {
  52675. if (start == 0 && end == this.nbParticles - 1) {
  52676. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52677. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52678. }
  52679. else {
  52680. if (this.mesh._boundingInfo) {
  52681. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52682. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52683. }
  52684. }
  52685. }
  52686. // particle loop
  52687. index = this.particles[start]._pos;
  52688. var vpos = (index / 3) | 0;
  52689. colorIndex = vpos * 4;
  52690. uvIndex = vpos * 2;
  52691. for (var p = start; p <= end; p++) {
  52692. this._particle = this.particles[p];
  52693. this._shape = this._particle._model._shape;
  52694. this._shapeUV = this._particle._model._shapeUV;
  52695. // call to custom user function to update the particle properties
  52696. this.updateParticle(this._particle);
  52697. // camera-particle distance for depth sorting
  52698. if (this._depthSort && this._depthSortParticles) {
  52699. var dsp = this.depthSortedParticles[p];
  52700. dsp.ind = this._particle._ind;
  52701. dsp.indicesLength = this._particle._model._indicesLength;
  52702. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52703. }
  52704. // skip the computations for inactive or already invisible particles
  52705. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52706. // increment indexes for the next particle
  52707. pt = this._shape.length;
  52708. index += pt * 3;
  52709. colorIndex += pt * 4;
  52710. uvIndex += pt * 2;
  52711. continue;
  52712. }
  52713. if (this._particle.isVisible) {
  52714. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52715. this._particleHasParent = (this._particle.parentId !== null);
  52716. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52717. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52718. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52719. // particle rotation matrix
  52720. if (this.billboard) {
  52721. this._particle.rotation.x = 0.0;
  52722. this._particle.rotation.y = 0.0;
  52723. }
  52724. if (this._computeParticleRotation || this.billboard) {
  52725. if (this._particle.rotationQuaternion) {
  52726. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52727. }
  52728. else {
  52729. this._yaw = this._particle.rotation.y;
  52730. this._pitch = this._particle.rotation.x;
  52731. this._roll = this._particle.rotation.z;
  52732. this._quaternionRotationYPR();
  52733. }
  52734. this._quaternionToRotationMatrix();
  52735. }
  52736. if (this._particleHasParent) {
  52737. this._parent = this.particles[this._particle.parentId];
  52738. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  52739. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  52740. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  52741. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52742. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52743. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52744. if (this._computeParticleRotation || this.billboard) {
  52745. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  52746. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  52747. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  52748. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  52749. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  52750. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  52751. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  52752. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  52753. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  52754. }
  52755. }
  52756. else {
  52757. this._particle._globalPosition.x = this._particle.position.x;
  52758. this._particle._globalPosition.y = this._particle.position.y;
  52759. this._particle._globalPosition.z = this._particle.position.z;
  52760. if (this._computeParticleRotation || this.billboard) {
  52761. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52762. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52763. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52764. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52765. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52766. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52767. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52768. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52769. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52770. }
  52771. }
  52772. if (this._particle.translateFromPivot) {
  52773. this._pivotBackTranslation.x = 0.0;
  52774. this._pivotBackTranslation.y = 0.0;
  52775. this._pivotBackTranslation.z = 0.0;
  52776. }
  52777. else {
  52778. this._pivotBackTranslation.x = this._scaledPivot.x;
  52779. this._pivotBackTranslation.y = this._scaledPivot.y;
  52780. this._pivotBackTranslation.z = this._scaledPivot.z;
  52781. }
  52782. // particle vertex loop
  52783. for (pt = 0; pt < this._shape.length; pt++) {
  52784. idx = index + pt * 3;
  52785. colidx = colorIndex + pt * 4;
  52786. uvidx = uvIndex + pt * 2;
  52787. this._vertex.x = this._shape[pt].x;
  52788. this._vertex.y = this._shape[pt].y;
  52789. this._vertex.z = this._shape[pt].z;
  52790. if (this._computeParticleVertex) {
  52791. this.updateParticleVertex(this._particle, this._vertex, pt);
  52792. }
  52793. // positions
  52794. this._vertex.x *= this._particle.scaling.x;
  52795. this._vertex.y *= this._particle.scaling.y;
  52796. this._vertex.z *= this._particle.scaling.z;
  52797. this._vertex.x -= this._scaledPivot.x;
  52798. this._vertex.y -= this._scaledPivot.y;
  52799. this._vertex.z -= this._scaledPivot.z;
  52800. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52801. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52802. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52803. this._rotated.x += this._pivotBackTranslation.x;
  52804. this._rotated.y += this._pivotBackTranslation.y;
  52805. this._rotated.z += this._pivotBackTranslation.z;
  52806. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52807. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52808. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52809. if (this._computeBoundingBox) {
  52810. if (this._positions32[idx] < this._minimum.x) {
  52811. this._minimum.x = this._positions32[idx];
  52812. }
  52813. if (this._positions32[idx] > this._maximum.x) {
  52814. this._maximum.x = this._positions32[idx];
  52815. }
  52816. if (this._positions32[idx + 1] < this._minimum.y) {
  52817. this._minimum.y = this._positions32[idx + 1];
  52818. }
  52819. if (this._positions32[idx + 1] > this._maximum.y) {
  52820. this._maximum.y = this._positions32[idx + 1];
  52821. }
  52822. if (this._positions32[idx + 2] < this._minimum.z) {
  52823. this._minimum.z = this._positions32[idx + 2];
  52824. }
  52825. if (this._positions32[idx + 2] > this._maximum.z) {
  52826. this._maximum.z = this._positions32[idx + 2];
  52827. }
  52828. }
  52829. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52830. if (!this._computeParticleVertex) {
  52831. this._normal.x = this._fixedNormal32[idx];
  52832. this._normal.y = this._fixedNormal32[idx + 1];
  52833. this._normal.z = this._fixedNormal32[idx + 2];
  52834. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52835. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52836. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52837. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52838. 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;
  52839. 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;
  52840. }
  52841. if (this._computeParticleColor && this._particle.color) {
  52842. this._colors32[colidx] = this._particle.color.r;
  52843. this._colors32[colidx + 1] = this._particle.color.g;
  52844. this._colors32[colidx + 2] = this._particle.color.b;
  52845. this._colors32[colidx + 3] = this._particle.color.a;
  52846. }
  52847. if (this._computeParticleTexture) {
  52848. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52849. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52850. }
  52851. }
  52852. }
  52853. else {
  52854. this._particle._stillInvisible = true; // mark the particle as invisible
  52855. for (pt = 0; pt < this._shape.length; pt++) {
  52856. idx = index + pt * 3;
  52857. colidx = colorIndex + pt * 4;
  52858. uvidx = uvIndex + pt * 2;
  52859. this._positions32[idx] = 0.0;
  52860. this._positions32[idx + 1] = 0.0;
  52861. this._positions32[idx + 2] = 0.0;
  52862. this._normals32[idx] = 0.0;
  52863. this._normals32[idx + 1] = 0.0;
  52864. this._normals32[idx + 2] = 0.0;
  52865. if (this._computeParticleColor && this._particle.color) {
  52866. this._colors32[colidx] = this._particle.color.r;
  52867. this._colors32[colidx + 1] = this._particle.color.g;
  52868. this._colors32[colidx + 2] = this._particle.color.b;
  52869. this._colors32[colidx + 3] = this._particle.color.a;
  52870. }
  52871. if (this._computeParticleTexture) {
  52872. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52873. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52874. }
  52875. }
  52876. }
  52877. // if the particle intersections must be computed : update the bbInfo
  52878. if (this._particlesIntersect) {
  52879. var bInfo = this._particle._boundingInfo;
  52880. var bBox = bInfo.boundingBox;
  52881. var bSphere = bInfo.boundingSphere;
  52882. if (!this._bSphereOnly) {
  52883. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52884. for (var b = 0; b < bBox.vectors.length; b++) {
  52885. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52886. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52887. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52888. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52889. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52890. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52891. 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;
  52892. 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;
  52893. 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;
  52894. }
  52895. bBox._update(this.mesh._worldMatrix);
  52896. }
  52897. // place and scale the particle bouding sphere in the SPS local system, then update it
  52898. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52899. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52900. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52901. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52902. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52903. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52904. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52905. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52906. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52907. 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));
  52908. bSphere._update(this.mesh._worldMatrix);
  52909. }
  52910. // increment indexes for the next particle
  52911. index = idx + 3;
  52912. colorIndex = colidx + 4;
  52913. uvIndex = uvidx + 2;
  52914. }
  52915. // if the VBO must be updated
  52916. if (update) {
  52917. if (this._computeParticleColor) {
  52918. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52919. }
  52920. if (this._computeParticleTexture) {
  52921. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52922. }
  52923. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52924. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52925. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52926. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52927. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52928. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52929. for (var i = 0; i < this._normals32.length; i++) {
  52930. this._fixedNormal32[i] = this._normals32[i];
  52931. }
  52932. }
  52933. if (!this.mesh.areNormalsFrozen) {
  52934. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52935. }
  52936. }
  52937. if (this._depthSort && this._depthSortParticles) {
  52938. this.depthSortedParticles.sort(this._depthSortFunction);
  52939. var dspl = this.depthSortedParticles.length;
  52940. var sorted = 0;
  52941. var lind = 0;
  52942. var sind = 0;
  52943. var sid = 0;
  52944. for (sorted = 0; sorted < dspl; sorted++) {
  52945. lind = this.depthSortedParticles[sorted].indicesLength;
  52946. sind = this.depthSortedParticles[sorted].ind;
  52947. for (var i = 0; i < lind; i++) {
  52948. this._indices32[sid] = this._indices[sind + i];
  52949. sid++;
  52950. }
  52951. }
  52952. this.mesh.updateIndices(this._indices32);
  52953. }
  52954. }
  52955. if (this._computeBoundingBox) {
  52956. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52957. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52958. }
  52959. this.afterUpdateParticles(start, end, update);
  52960. return this;
  52961. };
  52962. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52963. this._halfroll = this._roll * 0.5;
  52964. this._halfpitch = this._pitch * 0.5;
  52965. this._halfyaw = this._yaw * 0.5;
  52966. this._sinRoll = Math.sin(this._halfroll);
  52967. this._cosRoll = Math.cos(this._halfroll);
  52968. this._sinPitch = Math.sin(this._halfpitch);
  52969. this._cosPitch = Math.cos(this._halfpitch);
  52970. this._sinYaw = Math.sin(this._halfyaw);
  52971. this._cosYaw = Math.cos(this._halfyaw);
  52972. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52973. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52974. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52975. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52976. };
  52977. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52978. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52979. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52980. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52981. this._rotMatrix.m[3] = 0;
  52982. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52983. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52984. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52985. this._rotMatrix.m[7] = 0;
  52986. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52987. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52988. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52989. this._rotMatrix.m[11] = 0;
  52990. this._rotMatrix.m[12] = 0;
  52991. this._rotMatrix.m[13] = 0;
  52992. this._rotMatrix.m[14] = 0;
  52993. this._rotMatrix.m[15] = 1.0;
  52994. };
  52995. /**
  52996. * Disposes the SPS.
  52997. */
  52998. SolidParticleSystem.prototype.dispose = function () {
  52999. this.mesh.dispose();
  53000. this.vars = null;
  53001. // drop references to internal big arrays for the GC
  53002. this._positions = null;
  53003. this._indices = null;
  53004. this._normals = null;
  53005. this._uvs = null;
  53006. this._colors = null;
  53007. this._indices32 = null;
  53008. this._positions32 = null;
  53009. this._normals32 = null;
  53010. this._fixedNormal32 = null;
  53011. this._uvs32 = null;
  53012. this._colors32 = null;
  53013. this.pickedParticles = null;
  53014. };
  53015. /**
  53016. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53017. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53018. * @returns the SPS.
  53019. */
  53020. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53021. if (!this._isVisibilityBoxLocked) {
  53022. this.mesh.refreshBoundingInfo();
  53023. }
  53024. return this;
  53025. };
  53026. /**
  53027. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53028. * @param size the size (float) of the visibility box
  53029. * note : this doesn't lock the SPS mesh bounding box.
  53030. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53031. */
  53032. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53033. var vis = size / 2;
  53034. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53035. };
  53036. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53037. /**
  53038. * Gets whether the SPS as always visible or not
  53039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53040. */
  53041. get: function () {
  53042. return this._alwaysVisible;
  53043. },
  53044. /**
  53045. * Sets the SPS as always visible or not
  53046. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53047. */
  53048. set: function (val) {
  53049. this._alwaysVisible = val;
  53050. this.mesh.alwaysSelectAsActiveMesh = val;
  53051. },
  53052. enumerable: true,
  53053. configurable: true
  53054. });
  53055. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53056. /**
  53057. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53059. */
  53060. get: function () {
  53061. return this._isVisibilityBoxLocked;
  53062. },
  53063. /**
  53064. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53065. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53066. */
  53067. set: function (val) {
  53068. this._isVisibilityBoxLocked = val;
  53069. var boundingInfo = this.mesh.getBoundingInfo();
  53070. boundingInfo.isLocked = val;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53076. /**
  53077. * Gets if `setParticles()` computes the particle rotations or not.
  53078. * Default value : true. The SPS is faster when it's set to false.
  53079. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53080. */
  53081. get: function () {
  53082. return this._computeParticleRotation;
  53083. },
  53084. /**
  53085. * Tells to `setParticles()` to compute the particle rotations or not.
  53086. * Default value : true. The SPS is faster when it's set to false.
  53087. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53088. */
  53089. set: function (val) {
  53090. this._computeParticleRotation = val;
  53091. },
  53092. enumerable: true,
  53093. configurable: true
  53094. });
  53095. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53096. /**
  53097. * Gets if `setParticles()` computes the particle colors or not.
  53098. * Default value : true. The SPS is faster when it's set to false.
  53099. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53100. */
  53101. get: function () {
  53102. return this._computeParticleColor;
  53103. },
  53104. /**
  53105. * Tells to `setParticles()` to compute the particle colors or not.
  53106. * Default value : true. The SPS is faster when it's set to false.
  53107. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53108. */
  53109. set: function (val) {
  53110. this._computeParticleColor = val;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53116. /**
  53117. * Gets if `setParticles()` computes the particle textures or not.
  53118. * Default value : true. The SPS is faster when it's set to false.
  53119. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53120. */
  53121. get: function () {
  53122. return this._computeParticleTexture;
  53123. },
  53124. set: function (val) {
  53125. this._computeParticleTexture = val;
  53126. },
  53127. enumerable: true,
  53128. configurable: true
  53129. });
  53130. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53131. /**
  53132. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53133. * Default value : false. The SPS is faster when it's set to false.
  53134. * Note : the particle custom vertex positions aren't stored values.
  53135. */
  53136. get: function () {
  53137. return this._computeParticleVertex;
  53138. },
  53139. /**
  53140. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53141. * Default value : false. The SPS is faster when it's set to false.
  53142. * Note : the particle custom vertex positions aren't stored values.
  53143. */
  53144. set: function (val) {
  53145. this._computeParticleVertex = val;
  53146. },
  53147. enumerable: true,
  53148. configurable: true
  53149. });
  53150. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53151. /**
  53152. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53153. */
  53154. get: function () {
  53155. return this._computeBoundingBox;
  53156. },
  53157. /**
  53158. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53159. */
  53160. set: function (val) {
  53161. this._computeBoundingBox = val;
  53162. },
  53163. enumerable: true,
  53164. configurable: true
  53165. });
  53166. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53167. /**
  53168. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53169. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53170. * Default : `true`
  53171. */
  53172. get: function () {
  53173. return this._depthSortParticles;
  53174. },
  53175. /**
  53176. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53177. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53178. * Default : `true`
  53179. */
  53180. set: function (val) {
  53181. this._depthSortParticles = val;
  53182. },
  53183. enumerable: true,
  53184. configurable: true
  53185. });
  53186. // =======================================================================
  53187. // Particle behavior logic
  53188. // these following methods may be overwritten by the user to fit his needs
  53189. /**
  53190. * This function does nothing. It may be overwritten to set all the particle first values.
  53191. * The SPS doesn't call this function, you may have to call it by your own.
  53192. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53193. */
  53194. SolidParticleSystem.prototype.initParticles = function () {
  53195. };
  53196. /**
  53197. * This function does nothing. It may be overwritten to recycle a particle.
  53198. * The SPS doesn't call this function, you may have to call it by your own.
  53199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53200. * @param particle The particle to recycle
  53201. * @returns the recycled particle
  53202. */
  53203. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53204. return particle;
  53205. };
  53206. /**
  53207. * Updates a particle : this function should be overwritten by the user.
  53208. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53209. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53210. * @example : just set a particle position or velocity and recycle conditions
  53211. * @param particle The particle to update
  53212. * @returns the updated particle
  53213. */
  53214. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53215. return particle;
  53216. };
  53217. /**
  53218. * Updates a vertex of a particle : it can be overwritten by the user.
  53219. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53220. * @param particle the current particle
  53221. * @param vertex the current index of the current particle
  53222. * @param pt the index of the current vertex in the particle shape
  53223. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53224. * @example : just set a vertex particle position
  53225. * @returns the updated vertex
  53226. */
  53227. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53228. return vertex;
  53229. };
  53230. /**
  53231. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53232. * This does nothing and may be overwritten by the user.
  53233. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53234. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53235. * @param update the boolean update value actually passed to setParticles()
  53236. */
  53237. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53238. };
  53239. /**
  53240. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53241. * This will be passed three parameters.
  53242. * This does nothing and may be overwritten by the user.
  53243. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53244. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53245. * @param update the boolean update value actually passed to setParticles()
  53246. */
  53247. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53248. };
  53249. return SolidParticleSystem;
  53250. }());
  53251. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53252. })(BABYLON || (BABYLON = {}));
  53253. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53254. var BABYLON;
  53255. (function (BABYLON) {
  53256. var ShaderMaterial = /** @class */ (function (_super) {
  53257. __extends(ShaderMaterial, _super);
  53258. function ShaderMaterial(name, scene, shaderPath, options) {
  53259. var _this = _super.call(this, name, scene) || this;
  53260. _this._textures = {};
  53261. _this._textureArrays = {};
  53262. _this._floats = {};
  53263. _this._ints = {};
  53264. _this._floatsArrays = {};
  53265. _this._colors3 = {};
  53266. _this._colors3Arrays = {};
  53267. _this._colors4 = {};
  53268. _this._vectors2 = {};
  53269. _this._vectors3 = {};
  53270. _this._vectors4 = {};
  53271. _this._matrices = {};
  53272. _this._matrices3x3 = {};
  53273. _this._matrices2x2 = {};
  53274. _this._vectors2Arrays = {};
  53275. _this._vectors3Arrays = {};
  53276. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53277. _this._shaderPath = shaderPath;
  53278. options.needAlphaBlending = options.needAlphaBlending || false;
  53279. options.needAlphaTesting = options.needAlphaTesting || false;
  53280. options.attributes = options.attributes || ["position", "normal", "uv"];
  53281. options.uniforms = options.uniforms || ["worldViewProjection"];
  53282. options.uniformBuffers = options.uniformBuffers || [];
  53283. options.samplers = options.samplers || [];
  53284. options.defines = options.defines || [];
  53285. _this._options = options;
  53286. return _this;
  53287. }
  53288. ShaderMaterial.prototype.getClassName = function () {
  53289. return "ShaderMaterial";
  53290. };
  53291. ShaderMaterial.prototype.needAlphaBlending = function () {
  53292. return this._options.needAlphaBlending;
  53293. };
  53294. ShaderMaterial.prototype.needAlphaTesting = function () {
  53295. return this._options.needAlphaTesting;
  53296. };
  53297. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53298. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53299. this._options.uniforms.push(uniformName);
  53300. }
  53301. };
  53302. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53303. if (this._options.samplers.indexOf(name) === -1) {
  53304. this._options.samplers.push(name);
  53305. }
  53306. this._textures[name] = texture;
  53307. return this;
  53308. };
  53309. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53310. if (this._options.samplers.indexOf(name) === -1) {
  53311. this._options.samplers.push(name);
  53312. }
  53313. this._checkUniform(name);
  53314. this._textureArrays[name] = textures;
  53315. return this;
  53316. };
  53317. ShaderMaterial.prototype.setFloat = function (name, value) {
  53318. this._checkUniform(name);
  53319. this._floats[name] = value;
  53320. return this;
  53321. };
  53322. ShaderMaterial.prototype.setInt = function (name, value) {
  53323. this._checkUniform(name);
  53324. this._ints[name] = value;
  53325. return this;
  53326. };
  53327. ShaderMaterial.prototype.setFloats = function (name, value) {
  53328. this._checkUniform(name);
  53329. this._floatsArrays[name] = value;
  53330. return this;
  53331. };
  53332. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53333. this._checkUniform(name);
  53334. this._colors3[name] = value;
  53335. return this;
  53336. };
  53337. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53338. this._checkUniform(name);
  53339. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53340. color.toArray(arr, arr.length);
  53341. return arr;
  53342. }, []);
  53343. return this;
  53344. };
  53345. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53346. this._checkUniform(name);
  53347. this._colors4[name] = value;
  53348. return this;
  53349. };
  53350. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53351. this._checkUniform(name);
  53352. this._vectors2[name] = value;
  53353. return this;
  53354. };
  53355. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53356. this._checkUniform(name);
  53357. this._vectors3[name] = value;
  53358. return this;
  53359. };
  53360. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53361. this._checkUniform(name);
  53362. this._vectors4[name] = value;
  53363. return this;
  53364. };
  53365. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53366. this._checkUniform(name);
  53367. this._matrices[name] = value;
  53368. return this;
  53369. };
  53370. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53371. this._checkUniform(name);
  53372. this._matrices3x3[name] = value;
  53373. return this;
  53374. };
  53375. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53376. this._checkUniform(name);
  53377. this._matrices2x2[name] = value;
  53378. return this;
  53379. };
  53380. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53381. this._checkUniform(name);
  53382. this._vectors2Arrays[name] = value;
  53383. return this;
  53384. };
  53385. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53386. this._checkUniform(name);
  53387. this._vectors3Arrays[name] = value;
  53388. return this;
  53389. };
  53390. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53391. if (!mesh) {
  53392. return true;
  53393. }
  53394. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53395. return false;
  53396. }
  53397. return false;
  53398. };
  53399. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53400. var scene = this.getScene();
  53401. var engine = scene.getEngine();
  53402. if (!this.checkReadyOnEveryCall) {
  53403. if (this._renderId === scene.getRenderId()) {
  53404. if (this._checkCache(scene, mesh, useInstances)) {
  53405. return true;
  53406. }
  53407. }
  53408. }
  53409. // Instances
  53410. var defines = [];
  53411. var attribs = [];
  53412. var fallbacks = new BABYLON.EffectFallbacks();
  53413. if (useInstances) {
  53414. defines.push("#define INSTANCES");
  53415. }
  53416. for (var index = 0; index < this._options.defines.length; index++) {
  53417. defines.push(this._options.defines[index]);
  53418. }
  53419. for (var index = 0; index < this._options.attributes.length; index++) {
  53420. attribs.push(this._options.attributes[index]);
  53421. }
  53422. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53423. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53424. defines.push("#define VERTEXCOLOR");
  53425. }
  53426. // Bones
  53427. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53428. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53429. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53430. if (mesh.numBoneInfluencers > 4) {
  53431. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53432. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53433. }
  53434. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53435. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53436. fallbacks.addCPUSkinningFallback(0, mesh);
  53437. if (this._options.uniforms.indexOf("mBones") === -1) {
  53438. this._options.uniforms.push("mBones");
  53439. }
  53440. }
  53441. else {
  53442. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53443. }
  53444. // Textures
  53445. for (var name in this._textures) {
  53446. if (!this._textures[name].isReady()) {
  53447. return false;
  53448. }
  53449. }
  53450. // Alpha test
  53451. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53452. defines.push("#define ALPHATEST");
  53453. }
  53454. var previousEffect = this._effect;
  53455. var join = defines.join("\n");
  53456. this._effect = engine.createEffect(this._shaderPath, {
  53457. attributes: attribs,
  53458. uniformsNames: this._options.uniforms,
  53459. uniformBuffersNames: this._options.uniformBuffers,
  53460. samplers: this._options.samplers,
  53461. defines: join,
  53462. fallbacks: fallbacks,
  53463. onCompiled: this.onCompiled,
  53464. onError: this.onError
  53465. }, engine);
  53466. if (!this._effect.isReady()) {
  53467. return false;
  53468. }
  53469. if (previousEffect !== this._effect) {
  53470. scene.resetCachedMaterial();
  53471. }
  53472. this._renderId = scene.getRenderId();
  53473. return true;
  53474. };
  53475. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53476. var scene = this.getScene();
  53477. if (!this._effect) {
  53478. return;
  53479. }
  53480. if (this._options.uniforms.indexOf("world") !== -1) {
  53481. this._effect.setMatrix("world", world);
  53482. }
  53483. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53484. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53485. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53486. }
  53487. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53488. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53489. }
  53490. };
  53491. ShaderMaterial.prototype.bind = function (world, mesh) {
  53492. // Std values
  53493. this.bindOnlyWorldMatrix(world);
  53494. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53495. if (this._options.uniforms.indexOf("view") !== -1) {
  53496. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53497. }
  53498. if (this._options.uniforms.indexOf("projection") !== -1) {
  53499. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53500. }
  53501. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53502. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53503. }
  53504. // Bones
  53505. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53506. var name;
  53507. // Texture
  53508. for (name in this._textures) {
  53509. this._effect.setTexture(name, this._textures[name]);
  53510. }
  53511. // Texture arrays
  53512. for (name in this._textureArrays) {
  53513. this._effect.setTextureArray(name, this._textureArrays[name]);
  53514. }
  53515. // Int
  53516. for (name in this._ints) {
  53517. this._effect.setInt(name, this._ints[name]);
  53518. }
  53519. // Float
  53520. for (name in this._floats) {
  53521. this._effect.setFloat(name, this._floats[name]);
  53522. }
  53523. // Floats
  53524. for (name in this._floatsArrays) {
  53525. this._effect.setArray(name, this._floatsArrays[name]);
  53526. }
  53527. // Color3
  53528. for (name in this._colors3) {
  53529. this._effect.setColor3(name, this._colors3[name]);
  53530. }
  53531. for (name in this._colors3Arrays) {
  53532. this._effect.setArray3(name, this._colors3Arrays[name]);
  53533. }
  53534. // Color4
  53535. for (name in this._colors4) {
  53536. var color = this._colors4[name];
  53537. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53538. }
  53539. // Vector2
  53540. for (name in this._vectors2) {
  53541. this._effect.setVector2(name, this._vectors2[name]);
  53542. }
  53543. // Vector3
  53544. for (name in this._vectors3) {
  53545. this._effect.setVector3(name, this._vectors3[name]);
  53546. }
  53547. // Vector4
  53548. for (name in this._vectors4) {
  53549. this._effect.setVector4(name, this._vectors4[name]);
  53550. }
  53551. // Matrix
  53552. for (name in this._matrices) {
  53553. this._effect.setMatrix(name, this._matrices[name]);
  53554. }
  53555. // Matrix 3x3
  53556. for (name in this._matrices3x3) {
  53557. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53558. }
  53559. // Matrix 2x2
  53560. for (name in this._matrices2x2) {
  53561. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53562. }
  53563. // Vector2Array
  53564. for (name in this._vectors2Arrays) {
  53565. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53566. }
  53567. // Vector3Array
  53568. for (name in this._vectors3Arrays) {
  53569. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53570. }
  53571. }
  53572. this._afterBind(mesh);
  53573. };
  53574. ShaderMaterial.prototype.getActiveTextures = function () {
  53575. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53576. for (var name in this._textures) {
  53577. activeTextures.push(this._textures[name]);
  53578. }
  53579. for (var name in this._textureArrays) {
  53580. var array = this._textureArrays[name];
  53581. for (var index = 0; index < array.length; index++) {
  53582. activeTextures.push(array[index]);
  53583. }
  53584. }
  53585. return activeTextures;
  53586. };
  53587. ShaderMaterial.prototype.hasTexture = function (texture) {
  53588. if (_super.prototype.hasTexture.call(this, texture)) {
  53589. return true;
  53590. }
  53591. for (var name in this._textures) {
  53592. if (this._textures[name] === texture) {
  53593. return true;
  53594. }
  53595. }
  53596. for (var name in this._textureArrays) {
  53597. var array = this._textureArrays[name];
  53598. for (var index = 0; index < array.length; index++) {
  53599. if (array[index] === texture) {
  53600. return true;
  53601. }
  53602. }
  53603. }
  53604. return false;
  53605. };
  53606. ShaderMaterial.prototype.clone = function (name) {
  53607. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53608. return newShaderMaterial;
  53609. };
  53610. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53611. if (forceDisposeTextures) {
  53612. var name;
  53613. for (name in this._textures) {
  53614. this._textures[name].dispose();
  53615. }
  53616. for (name in this._textureArrays) {
  53617. var array = this._textureArrays[name];
  53618. for (var index = 0; index < array.length; index++) {
  53619. array[index].dispose();
  53620. }
  53621. }
  53622. }
  53623. this._textures = {};
  53624. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53625. };
  53626. ShaderMaterial.prototype.serialize = function () {
  53627. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53628. serializationObject.customType = "BABYLON.ShaderMaterial";
  53629. serializationObject.options = this._options;
  53630. serializationObject.shaderPath = this._shaderPath;
  53631. var name;
  53632. // Texture
  53633. serializationObject.textures = {};
  53634. for (name in this._textures) {
  53635. serializationObject.textures[name] = this._textures[name].serialize();
  53636. }
  53637. // Texture arrays
  53638. serializationObject.textureArrays = {};
  53639. for (name in this._textureArrays) {
  53640. serializationObject.textureArrays[name] = [];
  53641. var array = this._textureArrays[name];
  53642. for (var index = 0; index < array.length; index++) {
  53643. serializationObject.textureArrays[name].push(array[index].serialize());
  53644. }
  53645. }
  53646. // Float
  53647. serializationObject.floats = {};
  53648. for (name in this._floats) {
  53649. serializationObject.floats[name] = this._floats[name];
  53650. }
  53651. // Float s
  53652. serializationObject.FloatArrays = {};
  53653. for (name in this._floatsArrays) {
  53654. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53655. }
  53656. // Color3
  53657. serializationObject.colors3 = {};
  53658. for (name in this._colors3) {
  53659. serializationObject.colors3[name] = this._colors3[name].asArray();
  53660. }
  53661. // Color3 array
  53662. serializationObject.colors3Arrays = {};
  53663. for (name in this._colors3Arrays) {
  53664. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53665. }
  53666. // Color4
  53667. serializationObject.colors4 = {};
  53668. for (name in this._colors4) {
  53669. serializationObject.colors4[name] = this._colors4[name].asArray();
  53670. }
  53671. // Vector2
  53672. serializationObject.vectors2 = {};
  53673. for (name in this._vectors2) {
  53674. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53675. }
  53676. // Vector3
  53677. serializationObject.vectors3 = {};
  53678. for (name in this._vectors3) {
  53679. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53680. }
  53681. // Vector4
  53682. serializationObject.vectors4 = {};
  53683. for (name in this._vectors4) {
  53684. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53685. }
  53686. // Matrix
  53687. serializationObject.matrices = {};
  53688. for (name in this._matrices) {
  53689. serializationObject.matrices[name] = this._matrices[name].asArray();
  53690. }
  53691. // Matrix 3x3
  53692. serializationObject.matrices3x3 = {};
  53693. for (name in this._matrices3x3) {
  53694. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53695. }
  53696. // Matrix 2x2
  53697. serializationObject.matrices2x2 = {};
  53698. for (name in this._matrices2x2) {
  53699. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53700. }
  53701. // Vector2Array
  53702. serializationObject.vectors2Arrays = {};
  53703. for (name in this._vectors2Arrays) {
  53704. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53705. }
  53706. // Vector3Array
  53707. serializationObject.vectors3Arrays = {};
  53708. for (name in this._vectors3Arrays) {
  53709. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53710. }
  53711. return serializationObject;
  53712. };
  53713. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53714. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53715. var name;
  53716. // Texture
  53717. for (name in source.textures) {
  53718. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53719. }
  53720. // Texture arrays
  53721. for (name in source.textureArrays) {
  53722. var array = source.textureArrays[name];
  53723. var textureArray = new Array();
  53724. for (var index = 0; index < array.length; index++) {
  53725. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53726. }
  53727. material.setTextureArray(name, textureArray);
  53728. }
  53729. // Float
  53730. for (name in source.floats) {
  53731. material.setFloat(name, source.floats[name]);
  53732. }
  53733. // Float s
  53734. for (name in source.floatsArrays) {
  53735. material.setFloats(name, source.floatsArrays[name]);
  53736. }
  53737. // Color3
  53738. for (name in source.colors3) {
  53739. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53740. }
  53741. // Color3 arrays
  53742. for (name in source.colors3Arrays) {
  53743. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53744. if (i % 3 === 0) {
  53745. arr.push([num]);
  53746. }
  53747. else {
  53748. arr[arr.length - 1].push(num);
  53749. }
  53750. return arr;
  53751. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53752. material.setColor3Array(name, colors);
  53753. }
  53754. // Color4
  53755. for (name in source.colors4) {
  53756. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53757. }
  53758. // Vector2
  53759. for (name in source.vectors2) {
  53760. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53761. }
  53762. // Vector3
  53763. for (name in source.vectors3) {
  53764. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53765. }
  53766. // Vector4
  53767. for (name in source.vectors4) {
  53768. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53769. }
  53770. // Matrix
  53771. for (name in source.matrices) {
  53772. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53773. }
  53774. // Matrix 3x3
  53775. for (name in source.matrices3x3) {
  53776. material.setMatrix3x3(name, source.matrices3x3[name]);
  53777. }
  53778. // Matrix 2x2
  53779. for (name in source.matrices2x2) {
  53780. material.setMatrix2x2(name, source.matrices2x2[name]);
  53781. }
  53782. // Vector2Array
  53783. for (name in source.vectors2Arrays) {
  53784. material.setArray2(name, source.vectors2Arrays[name]);
  53785. }
  53786. // Vector3Array
  53787. for (name in source.vectors3Arrays) {
  53788. material.setArray3(name, source.vectors3Arrays[name]);
  53789. }
  53790. return material;
  53791. };
  53792. return ShaderMaterial;
  53793. }(BABYLON.Material));
  53794. BABYLON.ShaderMaterial = ShaderMaterial;
  53795. })(BABYLON || (BABYLON = {}));
  53796. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53797. var BABYLON;
  53798. (function (BABYLON) {
  53799. var GroundMesh = /** @class */ (function (_super) {
  53800. __extends(GroundMesh, _super);
  53801. function GroundMesh(name, scene) {
  53802. var _this = _super.call(this, name, scene) || this;
  53803. _this.generateOctree = false;
  53804. return _this;
  53805. }
  53806. GroundMesh.prototype.getClassName = function () {
  53807. return "GroundMesh";
  53808. };
  53809. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53810. get: function () {
  53811. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53817. get: function () {
  53818. return this._subdivisionsX;
  53819. },
  53820. enumerable: true,
  53821. configurable: true
  53822. });
  53823. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53824. get: function () {
  53825. return this._subdivisionsY;
  53826. },
  53827. enumerable: true,
  53828. configurable: true
  53829. });
  53830. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53831. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53832. this._subdivisionsX = chunksCount;
  53833. this._subdivisionsY = chunksCount;
  53834. this.subdivide(chunksCount);
  53835. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53836. };
  53837. /**
  53838. * Returns a height (y) value in the Worl system :
  53839. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53840. * Returns the ground y position if (x, z) are outside the ground surface.
  53841. */
  53842. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53843. var world = this.getWorldMatrix();
  53844. var invMat = BABYLON.Tmp.Matrix[5];
  53845. world.invertToRef(invMat);
  53846. var tmpVect = BABYLON.Tmp.Vector3[8];
  53847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53848. x = tmpVect.x;
  53849. z = tmpVect.z;
  53850. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53851. return this.position.y;
  53852. }
  53853. if (!this._heightQuads || this._heightQuads.length == 0) {
  53854. this._initHeightQuads();
  53855. this._computeHeightQuads();
  53856. }
  53857. var facet = this._getFacetAt(x, z);
  53858. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53859. // return y in the World system
  53860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53861. return tmpVect.y;
  53862. };
  53863. /**
  53864. * Returns a normalized vector (Vector3) orthogonal to the ground
  53865. * at the ground coordinates (x, z) expressed in the World system.
  53866. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53867. */
  53868. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53869. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53870. this.getNormalAtCoordinatesToRef(x, z, normal);
  53871. return normal;
  53872. };
  53873. /**
  53874. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53875. * at the ground coordinates (x, z) expressed in the World system.
  53876. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53877. * Returns the GroundMesh.
  53878. */
  53879. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53880. var world = this.getWorldMatrix();
  53881. var tmpMat = BABYLON.Tmp.Matrix[5];
  53882. world.invertToRef(tmpMat);
  53883. var tmpVect = BABYLON.Tmp.Vector3[8];
  53884. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53885. x = tmpVect.x;
  53886. z = tmpVect.z;
  53887. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53888. return this;
  53889. }
  53890. if (!this._heightQuads || this._heightQuads.length == 0) {
  53891. this._initHeightQuads();
  53892. this._computeHeightQuads();
  53893. }
  53894. var facet = this._getFacetAt(x, z);
  53895. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53896. return this;
  53897. };
  53898. /**
  53899. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53900. * if the ground has been updated.
  53901. * This can be used in the render loop.
  53902. * Returns the GroundMesh.
  53903. */
  53904. GroundMesh.prototype.updateCoordinateHeights = function () {
  53905. if (!this._heightQuads || this._heightQuads.length == 0) {
  53906. this._initHeightQuads();
  53907. }
  53908. this._computeHeightQuads();
  53909. return this;
  53910. };
  53911. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53912. GroundMesh.prototype._getFacetAt = function (x, z) {
  53913. // retrieve col and row from x, z coordinates in the ground local system
  53914. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53915. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53916. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53917. var facet;
  53918. if (z < quad.slope.x * x + quad.slope.y) {
  53919. facet = quad.facet1;
  53920. }
  53921. else {
  53922. facet = quad.facet2;
  53923. }
  53924. return facet;
  53925. };
  53926. // Creates and populates the heightMap array with "facet" elements :
  53927. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53928. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53929. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53930. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53931. // Returns the GroundMesh.
  53932. GroundMesh.prototype._initHeightQuads = function () {
  53933. var subdivisionsX = this._subdivisionsX;
  53934. var subdivisionsY = this._subdivisionsY;
  53935. this._heightQuads = new Array();
  53936. for (var row = 0; row < subdivisionsY; row++) {
  53937. for (var col = 0; col < subdivisionsX; col++) {
  53938. 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) };
  53939. this._heightQuads[row * subdivisionsX + col] = quad;
  53940. }
  53941. }
  53942. return this;
  53943. };
  53944. // Compute each quad element values and update the the heightMap array :
  53945. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53946. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53947. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53948. // Returns the GroundMesh.
  53949. GroundMesh.prototype._computeHeightQuads = function () {
  53950. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53951. if (!positions) {
  53952. return this;
  53953. }
  53954. var v1 = BABYLON.Tmp.Vector3[3];
  53955. var v2 = BABYLON.Tmp.Vector3[2];
  53956. var v3 = BABYLON.Tmp.Vector3[1];
  53957. var v4 = BABYLON.Tmp.Vector3[0];
  53958. var v1v2 = BABYLON.Tmp.Vector3[4];
  53959. var v1v3 = BABYLON.Tmp.Vector3[5];
  53960. var v1v4 = BABYLON.Tmp.Vector3[6];
  53961. var norm1 = BABYLON.Tmp.Vector3[7];
  53962. var norm2 = BABYLON.Tmp.Vector3[8];
  53963. var i = 0;
  53964. var j = 0;
  53965. var k = 0;
  53966. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53967. var h = 0;
  53968. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53969. var d2 = 0;
  53970. var subdivisionsX = this._subdivisionsX;
  53971. var subdivisionsY = this._subdivisionsY;
  53972. for (var row = 0; row < subdivisionsY; row++) {
  53973. for (var col = 0; col < subdivisionsX; col++) {
  53974. i = col * 3;
  53975. j = row * (subdivisionsX + 1) * 3;
  53976. k = (row + 1) * (subdivisionsX + 1) * 3;
  53977. v1.x = positions[j + i];
  53978. v1.y = positions[j + i + 1];
  53979. v1.z = positions[j + i + 2];
  53980. v2.x = positions[j + i + 3];
  53981. v2.y = positions[j + i + 4];
  53982. v2.z = positions[j + i + 5];
  53983. v3.x = positions[k + i];
  53984. v3.y = positions[k + i + 1];
  53985. v3.z = positions[k + i + 2];
  53986. v4.x = positions[k + i + 3];
  53987. v4.y = positions[k + i + 4];
  53988. v4.z = positions[k + i + 5];
  53989. // 2D slope V1V4
  53990. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53991. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53992. // facet equations :
  53993. // we compute each facet normal vector
  53994. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53995. // we compute the value d by applying the equation to v1 which belongs to the plane
  53996. // then we store the facet equation in a Vector4
  53997. v2.subtractToRef(v1, v1v2);
  53998. v3.subtractToRef(v1, v1v3);
  53999. v4.subtractToRef(v1, v1v4);
  54000. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54001. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54002. norm1.normalize();
  54003. norm2.normalize();
  54004. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54005. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54006. var quad = this._heightQuads[row * subdivisionsX + col];
  54007. quad.slope.copyFromFloats(cd, h);
  54008. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54009. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54010. }
  54011. }
  54012. return this;
  54013. };
  54014. GroundMesh.prototype.serialize = function (serializationObject) {
  54015. _super.prototype.serialize.call(this, serializationObject);
  54016. serializationObject.subdivisionsX = this._subdivisionsX;
  54017. serializationObject.subdivisionsY = this._subdivisionsY;
  54018. serializationObject.minX = this._minX;
  54019. serializationObject.maxX = this._maxX;
  54020. serializationObject.minZ = this._minZ;
  54021. serializationObject.maxZ = this._maxZ;
  54022. serializationObject.width = this._width;
  54023. serializationObject.height = this._height;
  54024. };
  54025. GroundMesh.Parse = function (parsedMesh, scene) {
  54026. var result = new GroundMesh(parsedMesh.name, scene);
  54027. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54028. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54029. result._minX = parsedMesh.minX;
  54030. result._maxX = parsedMesh.maxX;
  54031. result._minZ = parsedMesh.minZ;
  54032. result._maxZ = parsedMesh.maxZ;
  54033. result._width = parsedMesh.width;
  54034. result._height = parsedMesh.height;
  54035. return result;
  54036. };
  54037. return GroundMesh;
  54038. }(BABYLON.Mesh));
  54039. BABYLON.GroundMesh = GroundMesh;
  54040. })(BABYLON || (BABYLON = {}));
  54041. //# sourceMappingURL=babylon.groundMesh.js.map
  54042. var BABYLON;
  54043. (function (BABYLON) {
  54044. /**
  54045. * Creates an instance based on a source mesh.
  54046. */
  54047. var InstancedMesh = /** @class */ (function (_super) {
  54048. __extends(InstancedMesh, _super);
  54049. function InstancedMesh(name, source) {
  54050. var _this = _super.call(this, name, source.getScene()) || this;
  54051. source.instances.push(_this);
  54052. _this._sourceMesh = source;
  54053. _this.position.copyFrom(source.position);
  54054. _this.rotation.copyFrom(source.rotation);
  54055. _this.scaling.copyFrom(source.scaling);
  54056. if (source.rotationQuaternion) {
  54057. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54058. }
  54059. _this.infiniteDistance = source.infiniteDistance;
  54060. _this.setPivotMatrix(source.getPivotMatrix());
  54061. _this.refreshBoundingInfo();
  54062. _this._syncSubMeshes();
  54063. return _this;
  54064. }
  54065. /**
  54066. * Returns the string "InstancedMesh".
  54067. */
  54068. InstancedMesh.prototype.getClassName = function () {
  54069. return "InstancedMesh";
  54070. };
  54071. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54072. // Methods
  54073. get: function () {
  54074. return this._sourceMesh.receiveShadows;
  54075. },
  54076. enumerable: true,
  54077. configurable: true
  54078. });
  54079. Object.defineProperty(InstancedMesh.prototype, "material", {
  54080. get: function () {
  54081. return this._sourceMesh.material;
  54082. },
  54083. enumerable: true,
  54084. configurable: true
  54085. });
  54086. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54087. get: function () {
  54088. return this._sourceMesh.visibility;
  54089. },
  54090. enumerable: true,
  54091. configurable: true
  54092. });
  54093. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54094. get: function () {
  54095. return this._sourceMesh.skeleton;
  54096. },
  54097. enumerable: true,
  54098. configurable: true
  54099. });
  54100. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54101. get: function () {
  54102. return this._sourceMesh.renderingGroupId;
  54103. },
  54104. enumerable: true,
  54105. configurable: true
  54106. });
  54107. /**
  54108. * Returns the total number of vertices (integer).
  54109. */
  54110. InstancedMesh.prototype.getTotalVertices = function () {
  54111. return this._sourceMesh.getTotalVertices();
  54112. };
  54113. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54114. get: function () {
  54115. return this._sourceMesh;
  54116. },
  54117. enumerable: true,
  54118. configurable: true
  54119. });
  54120. /**
  54121. * Is this node ready to be used/rendered
  54122. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54123. * @return {boolean} is it ready
  54124. */
  54125. InstancedMesh.prototype.isReady = function (completeCheck) {
  54126. if (completeCheck === void 0) { completeCheck = false; }
  54127. return this._sourceMesh.isReady(completeCheck, true);
  54128. };
  54129. /**
  54130. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54131. */
  54132. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54133. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54134. };
  54135. /**
  54136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54138. * The `data` are either a numeric array either a Float32Array.
  54139. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54140. * 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).
  54141. * Note that a new underlying VertexBuffer object is created each call.
  54142. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54143. *
  54144. * Possible `kind` values :
  54145. * - BABYLON.VertexBuffer.PositionKind
  54146. * - BABYLON.VertexBuffer.UVKind
  54147. * - BABYLON.VertexBuffer.UV2Kind
  54148. * - BABYLON.VertexBuffer.UV3Kind
  54149. * - BABYLON.VertexBuffer.UV4Kind
  54150. * - BABYLON.VertexBuffer.UV5Kind
  54151. * - BABYLON.VertexBuffer.UV6Kind
  54152. * - BABYLON.VertexBuffer.ColorKind
  54153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54157. *
  54158. * Returns the Mesh.
  54159. */
  54160. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54161. if (this.sourceMesh) {
  54162. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54163. }
  54164. return this.sourceMesh;
  54165. };
  54166. /**
  54167. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54168. * If the mesh has no geometry, it is simply returned as it is.
  54169. * The `data` are either a numeric array either a Float32Array.
  54170. * No new underlying VertexBuffer object is created.
  54171. * 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.
  54172. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54173. *
  54174. * Possible `kind` values :
  54175. * - BABYLON.VertexBuffer.PositionKind
  54176. * - BABYLON.VertexBuffer.UVKind
  54177. * - BABYLON.VertexBuffer.UV2Kind
  54178. * - BABYLON.VertexBuffer.UV3Kind
  54179. * - BABYLON.VertexBuffer.UV4Kind
  54180. * - BABYLON.VertexBuffer.UV5Kind
  54181. * - BABYLON.VertexBuffer.UV6Kind
  54182. * - BABYLON.VertexBuffer.ColorKind
  54183. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54184. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54185. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54186. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54187. *
  54188. * Returns the Mesh.
  54189. */
  54190. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54191. if (this.sourceMesh) {
  54192. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54193. }
  54194. return this.sourceMesh;
  54195. };
  54196. /**
  54197. * Sets the mesh indices.
  54198. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54199. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54200. * This method creates a new index buffer each call.
  54201. * Returns the Mesh.
  54202. */
  54203. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54204. if (totalVertices === void 0) { totalVertices = null; }
  54205. if (this.sourceMesh) {
  54206. this.sourceMesh.setIndices(indices, totalVertices);
  54207. }
  54208. return this.sourceMesh;
  54209. };
  54210. /**
  54211. * Boolean : True if the mesh owns the requested kind of data.
  54212. */
  54213. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54214. return this._sourceMesh.isVerticesDataPresent(kind);
  54215. };
  54216. /**
  54217. * Returns an array of indices (IndicesArray).
  54218. */
  54219. InstancedMesh.prototype.getIndices = function () {
  54220. return this._sourceMesh.getIndices();
  54221. };
  54222. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54223. get: function () {
  54224. return this._sourceMesh._positions;
  54225. },
  54226. enumerable: true,
  54227. configurable: true
  54228. });
  54229. /**
  54230. * Sets a new updated BoundingInfo to the mesh.
  54231. * Returns the mesh.
  54232. */
  54233. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54234. var meshBB = this._sourceMesh.getBoundingInfo();
  54235. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54236. this._updateBoundingInfo();
  54237. return this;
  54238. };
  54239. InstancedMesh.prototype._preActivate = function () {
  54240. if (this._currentLOD) {
  54241. this._currentLOD._preActivate();
  54242. }
  54243. return this;
  54244. };
  54245. InstancedMesh.prototype._activate = function (renderId) {
  54246. if (this._currentLOD) {
  54247. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54248. }
  54249. return this;
  54250. };
  54251. /**
  54252. * Returns the current associated LOD AbstractMesh.
  54253. */
  54254. InstancedMesh.prototype.getLOD = function (camera) {
  54255. if (!camera) {
  54256. return this;
  54257. }
  54258. var boundingInfo = this.getBoundingInfo();
  54259. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54260. if (this._currentLOD === this.sourceMesh) {
  54261. return this;
  54262. }
  54263. return this._currentLOD;
  54264. };
  54265. InstancedMesh.prototype._syncSubMeshes = function () {
  54266. this.releaseSubMeshes();
  54267. if (this._sourceMesh.subMeshes) {
  54268. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54269. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54270. }
  54271. }
  54272. return this;
  54273. };
  54274. InstancedMesh.prototype._generatePointsArray = function () {
  54275. return this._sourceMesh._generatePointsArray();
  54276. };
  54277. /**
  54278. * Creates a new InstancedMesh from the current mesh.
  54279. * - name (string) : the cloned mesh name
  54280. * - newParent (optional Node) : the optional Node to parent the clone to.
  54281. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54282. *
  54283. * Returns the clone.
  54284. */
  54285. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54286. var result = this._sourceMesh.createInstance(name);
  54287. // Deep copy
  54288. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54289. // Bounding info
  54290. this.refreshBoundingInfo();
  54291. // Parent
  54292. if (newParent) {
  54293. result.parent = newParent;
  54294. }
  54295. if (!doNotCloneChildren) {
  54296. // Children
  54297. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54298. var mesh = this.getScene().meshes[index];
  54299. if (mesh.parent === this) {
  54300. mesh.clone(mesh.name, result);
  54301. }
  54302. }
  54303. }
  54304. result.computeWorldMatrix(true);
  54305. return result;
  54306. };
  54307. /**
  54308. * Disposes the InstancedMesh.
  54309. * Returns nothing.
  54310. */
  54311. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54312. // Remove from mesh
  54313. var index = this._sourceMesh.instances.indexOf(this);
  54314. this._sourceMesh.instances.splice(index, 1);
  54315. _super.prototype.dispose.call(this, doNotRecurse);
  54316. };
  54317. return InstancedMesh;
  54318. }(BABYLON.AbstractMesh));
  54319. BABYLON.InstancedMesh = InstancedMesh;
  54320. })(BABYLON || (BABYLON = {}));
  54321. //# sourceMappingURL=babylon.instancedMesh.js.map
  54322. var BABYLON;
  54323. (function (BABYLON) {
  54324. var LinesMesh = /** @class */ (function (_super) {
  54325. __extends(LinesMesh, _super);
  54326. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54327. if (scene === void 0) { scene = null; }
  54328. if (parent === void 0) { parent = null; }
  54329. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54330. _this.useVertexColor = useVertexColor;
  54331. _this.useVertexAlpha = useVertexAlpha;
  54332. _this.color = new BABYLON.Color3(1, 1, 1);
  54333. _this.alpha = 1;
  54334. if (source) {
  54335. _this.color = source.color.clone();
  54336. _this.alpha = source.alpha;
  54337. _this.useVertexColor = source.useVertexColor;
  54338. _this.useVertexAlpha = source.useVertexAlpha;
  54339. }
  54340. _this._intersectionThreshold = 0.1;
  54341. var defines = [];
  54342. var options = {
  54343. attributes: [BABYLON.VertexBuffer.PositionKind],
  54344. uniforms: ["world", "viewProjection"],
  54345. needAlphaBlending: true,
  54346. defines: defines
  54347. };
  54348. if (useVertexAlpha === false) {
  54349. options.needAlphaBlending = false;
  54350. }
  54351. if (!useVertexColor) {
  54352. options.uniforms.push("color");
  54353. }
  54354. else {
  54355. options.defines.push("#define VERTEXCOLOR");
  54356. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54357. }
  54358. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54359. return _this;
  54360. }
  54361. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54362. /**
  54363. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54364. * This margin is expressed in world space coordinates, so its value may vary.
  54365. * Default value is 0.1
  54366. * @returns the intersection Threshold value.
  54367. */
  54368. get: function () {
  54369. return this._intersectionThreshold;
  54370. },
  54371. /**
  54372. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54373. * This margin is expressed in world space coordinates, so its value may vary.
  54374. * @param value the new threshold to apply
  54375. */
  54376. set: function (value) {
  54377. if (this._intersectionThreshold === value) {
  54378. return;
  54379. }
  54380. this._intersectionThreshold = value;
  54381. if (this.geometry) {
  54382. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54383. }
  54384. },
  54385. enumerable: true,
  54386. configurable: true
  54387. });
  54388. /**
  54389. * Returns the string "LineMesh"
  54390. */
  54391. LinesMesh.prototype.getClassName = function () {
  54392. return "LinesMesh";
  54393. };
  54394. Object.defineProperty(LinesMesh.prototype, "material", {
  54395. get: function () {
  54396. return this._colorShader;
  54397. },
  54398. set: function (value) {
  54399. // Do nothing
  54400. },
  54401. enumerable: true,
  54402. configurable: true
  54403. });
  54404. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54405. get: function () {
  54406. return false;
  54407. },
  54408. enumerable: true,
  54409. configurable: true
  54410. });
  54411. LinesMesh.prototype.createInstance = function (name) {
  54412. throw new Error("LinesMeshes do not support createInstance.");
  54413. };
  54414. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54415. if (!this._geometry) {
  54416. return this;
  54417. }
  54418. // VBOs
  54419. this._geometry._bind(this._colorShader.getEffect());
  54420. // Color
  54421. if (!this.useVertexColor) {
  54422. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54423. }
  54424. return this;
  54425. };
  54426. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54427. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54428. return this;
  54429. }
  54430. var engine = this.getScene().getEngine();
  54431. // Draw order
  54432. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54433. return this;
  54434. };
  54435. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54436. this._colorShader.dispose();
  54437. _super.prototype.dispose.call(this, doNotRecurse);
  54438. };
  54439. /**
  54440. * Returns a new LineMesh object cloned from the current one.
  54441. */
  54442. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54443. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54444. };
  54445. return LinesMesh;
  54446. }(BABYLON.Mesh));
  54447. BABYLON.LinesMesh = LinesMesh;
  54448. })(BABYLON || (BABYLON = {}));
  54449. //# sourceMappingURL=babylon.linesMesh.js.map
  54450. var BABYLON;
  54451. (function (BABYLON) {
  54452. var MeshBuilder = /** @class */ (function () {
  54453. function MeshBuilder() {
  54454. }
  54455. MeshBuilder.updateSideOrientation = function (orientation) {
  54456. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54457. return BABYLON.Mesh.DOUBLESIDE;
  54458. }
  54459. if (orientation === undefined || orientation === null) {
  54460. return BABYLON.Mesh.FRONTSIDE;
  54461. }
  54462. return orientation;
  54463. };
  54464. /**
  54465. * Creates a box mesh.
  54466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54467. * The parameter `size` sets the size (float) of each box side (default 1).
  54468. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54469. * 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).
  54470. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54472. * 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).
  54473. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54475. */
  54476. MeshBuilder.CreateBox = function (name, options, scene) {
  54477. if (scene === void 0) { scene = null; }
  54478. var box = new BABYLON.Mesh(name, scene);
  54479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54480. box._originalBuilderSideOrientation = options.sideOrientation;
  54481. var vertexData = BABYLON.VertexData.CreateBox(options);
  54482. vertexData.applyToMesh(box, options.updatable);
  54483. return box;
  54484. };
  54485. /**
  54486. * Creates a sphere mesh.
  54487. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54488. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54489. * 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`).
  54490. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54491. * 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
  54492. * 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).
  54493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54494. * 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).
  54495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54497. */
  54498. MeshBuilder.CreateSphere = function (name, options, scene) {
  54499. var sphere = new BABYLON.Mesh(name, scene);
  54500. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54501. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54502. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54503. vertexData.applyToMesh(sphere, options.updatable);
  54504. return sphere;
  54505. };
  54506. /**
  54507. * Creates a plane polygonal mesh. By default, this is a disc.
  54508. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54509. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54510. * 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.
  54511. * 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
  54512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54513. * 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).
  54514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54516. */
  54517. MeshBuilder.CreateDisc = function (name, options, scene) {
  54518. if (scene === void 0) { scene = null; }
  54519. var disc = new BABYLON.Mesh(name, scene);
  54520. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54521. disc._originalBuilderSideOrientation = options.sideOrientation;
  54522. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54523. vertexData.applyToMesh(disc, options.updatable);
  54524. return disc;
  54525. };
  54526. /**
  54527. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54528. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54529. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54530. * 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`).
  54531. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54532. * 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.
  54533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54534. * 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).
  54535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54537. */
  54538. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54539. var sphere = new BABYLON.Mesh(name, scene);
  54540. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54541. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54542. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54543. vertexData.applyToMesh(sphere, options.updatable);
  54544. return sphere;
  54545. };
  54546. ;
  54547. /**
  54548. * Creates a ribbon mesh.
  54549. * 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.
  54550. *
  54551. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54552. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54553. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54554. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54555. * 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.
  54556. * 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.
  54557. * 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
  54558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54559. * 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).
  54560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54561. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54562. * 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.
  54563. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54564. * 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
  54565. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54566. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54568. */
  54569. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54570. if (scene === void 0) { scene = null; }
  54571. var pathArray = options.pathArray;
  54572. var closeArray = options.closeArray;
  54573. var closePath = options.closePath;
  54574. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54575. var instance = options.instance;
  54576. var updatable = options.updatable;
  54577. if (instance) {
  54578. // positionFunction : ribbon case
  54579. // only pathArray and sideOrientation parameters are taken into account for positions update
  54580. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54581. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54582. var positionFunction = function (positions) {
  54583. var minlg = pathArray[0].length;
  54584. var i = 0;
  54585. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54586. for (var si = 1; si <= ns; si++) {
  54587. for (var p = 0; p < pathArray.length; p++) {
  54588. var path = pathArray[p];
  54589. var l = path.length;
  54590. minlg = (minlg < l) ? minlg : l;
  54591. var j = 0;
  54592. while (j < minlg) {
  54593. positions[i] = path[j].x;
  54594. positions[i + 1] = path[j].y;
  54595. positions[i + 2] = path[j].z;
  54596. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54597. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54598. }
  54599. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54600. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54601. }
  54602. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54603. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54604. }
  54605. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54606. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54607. }
  54608. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54609. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54610. }
  54611. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54612. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54613. }
  54614. j++;
  54615. i += 3;
  54616. }
  54617. if (instance._closePath) {
  54618. positions[i] = path[0].x;
  54619. positions[i + 1] = path[0].y;
  54620. positions[i + 2] = path[0].z;
  54621. i += 3;
  54622. }
  54623. }
  54624. }
  54625. };
  54626. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54627. positionFunction(positions);
  54628. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54629. instance._boundingInfo.update(instance._worldMatrix);
  54630. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54631. if (options.colors) {
  54632. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54633. for (var c = 0; c < options.colors.length; c++) {
  54634. colors[c * 4] = options.colors[c].r;
  54635. colors[c * 4 + 1] = options.colors[c].g;
  54636. colors[c * 4 + 2] = options.colors[c].b;
  54637. colors[c * 4 + 3] = options.colors[c].a;
  54638. }
  54639. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54640. }
  54641. if (options.uvs) {
  54642. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54643. for (var i = 0; i < options.uvs.length; i++) {
  54644. uvs[i * 2] = options.uvs[i].x;
  54645. uvs[i * 2 + 1] = options.uvs[i].y;
  54646. }
  54647. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54648. }
  54649. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54650. var indices = instance.getIndices();
  54651. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54652. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54653. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54654. if (instance._closePath) {
  54655. var indexFirst = 0;
  54656. var indexLast = 0;
  54657. for (var p = 0; p < pathArray.length; p++) {
  54658. indexFirst = instance._idx[p] * 3;
  54659. if (p + 1 < pathArray.length) {
  54660. indexLast = (instance._idx[p + 1] - 1) * 3;
  54661. }
  54662. else {
  54663. indexLast = normals.length - 3;
  54664. }
  54665. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54666. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54667. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54668. normals[indexLast] = normals[indexFirst];
  54669. normals[indexLast + 1] = normals[indexFirst + 1];
  54670. normals[indexLast + 2] = normals[indexFirst + 2];
  54671. }
  54672. }
  54673. if (!(instance.areNormalsFrozen)) {
  54674. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54675. }
  54676. }
  54677. return instance;
  54678. }
  54679. else {
  54680. var ribbon = new BABYLON.Mesh(name, scene);
  54681. ribbon._originalBuilderSideOrientation = sideOrientation;
  54682. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54683. if (closePath) {
  54684. ribbon._idx = vertexData._idx;
  54685. }
  54686. ribbon._closePath = closePath;
  54687. ribbon._closeArray = closeArray;
  54688. vertexData.applyToMesh(ribbon, updatable);
  54689. return ribbon;
  54690. }
  54691. };
  54692. /**
  54693. * Creates a cylinder or a cone mesh.
  54694. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54695. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54696. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54697. * 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.
  54698. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54699. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54700. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54701. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54702. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54703. * 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).
  54704. * 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
  54705. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54706. * 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
  54707. * 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.
  54708. * If `enclose` is false, a ring surface is one element.
  54709. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54710. * 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
  54711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54712. * 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).
  54713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54715. */
  54716. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54717. var cylinder = new BABYLON.Mesh(name, scene);
  54718. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54719. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54720. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54721. vertexData.applyToMesh(cylinder, options.updatable);
  54722. return cylinder;
  54723. };
  54724. /**
  54725. * Creates a torus mesh.
  54726. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54727. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54728. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54729. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54731. * 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).
  54732. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54734. */
  54735. MeshBuilder.CreateTorus = function (name, options, scene) {
  54736. var torus = new BABYLON.Mesh(name, scene);
  54737. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54738. torus._originalBuilderSideOrientation = options.sideOrientation;
  54739. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54740. vertexData.applyToMesh(torus, options.updatable);
  54741. return torus;
  54742. };
  54743. /**
  54744. * Creates a torus knot mesh.
  54745. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54746. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54747. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54748. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54749. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54751. * 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).
  54752. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54754. */
  54755. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54756. var torusKnot = new BABYLON.Mesh(name, scene);
  54757. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54758. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54759. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54760. vertexData.applyToMesh(torusKnot, options.updatable);
  54761. return torusKnot;
  54762. };
  54763. /**
  54764. * Creates a line system mesh.
  54765. * A line system is a pool of many lines gathered in a single mesh.
  54766. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54767. * 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.
  54768. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54769. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54770. * 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
  54771. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54772. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54773. * 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
  54774. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54776. */
  54777. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54778. var instance = options.instance;
  54779. var lines = options.lines;
  54780. var colors = options.colors;
  54781. if (instance) {
  54782. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54783. var vertexColor;
  54784. var lineColors;
  54785. if (colors) {
  54786. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54787. }
  54788. var i = 0;
  54789. var c = 0;
  54790. for (var l = 0; l < lines.length; l++) {
  54791. var points = lines[l];
  54792. for (var p = 0; p < points.length; p++) {
  54793. positions[i] = points[p].x;
  54794. positions[i + 1] = points[p].y;
  54795. positions[i + 2] = points[p].z;
  54796. if (colors && vertexColor) {
  54797. lineColors = colors[l];
  54798. vertexColor[c] = lineColors[p].r;
  54799. vertexColor[c + 1] = lineColors[p].g;
  54800. vertexColor[c + 2] = lineColors[p].b;
  54801. vertexColor[c + 3] = lineColors[p].a;
  54802. c += 4;
  54803. }
  54804. i += 3;
  54805. }
  54806. }
  54807. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54808. if (colors && vertexColor) {
  54809. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54810. }
  54811. return instance;
  54812. }
  54813. // line system creation
  54814. var useVertexColor = (colors) ? true : false;
  54815. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54816. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54817. vertexData.applyToMesh(lineSystem, options.updatable);
  54818. return lineSystem;
  54819. };
  54820. /**
  54821. * Creates a line mesh.
  54822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54823. * 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.
  54824. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54825. * The parameter `points` is an array successive Vector3.
  54826. * 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
  54827. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54828. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54829. * When updating an instance, remember that only point positions can change, not the number of points.
  54830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54831. */
  54832. MeshBuilder.CreateLines = function (name, options, scene) {
  54833. if (scene === void 0) { scene = null; }
  54834. var colors = (options.colors) ? [options.colors] : null;
  54835. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54836. return lines;
  54837. };
  54838. /**
  54839. * Creates a dashed line mesh.
  54840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54841. * 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.
  54842. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54843. * The parameter `points` is an array successive Vector3.
  54844. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54845. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54846. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54847. * 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
  54848. * When updating an instance, remember that only point positions can change, not the number of points.
  54849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54850. */
  54851. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54852. if (scene === void 0) { scene = null; }
  54853. var points = options.points;
  54854. var instance = options.instance;
  54855. var gapSize = options.gapSize || 1;
  54856. var dashSize = options.dashSize || 3;
  54857. if (instance) {
  54858. var positionFunction = function (positions) {
  54859. var curvect = BABYLON.Vector3.Zero();
  54860. var nbSeg = positions.length / 6;
  54861. var lg = 0;
  54862. var nb = 0;
  54863. var shft = 0;
  54864. var dashshft = 0;
  54865. var curshft = 0;
  54866. var p = 0;
  54867. var i = 0;
  54868. var j = 0;
  54869. for (i = 0; i < points.length - 1; i++) {
  54870. points[i + 1].subtractToRef(points[i], curvect);
  54871. lg += curvect.length();
  54872. }
  54873. shft = lg / nbSeg;
  54874. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54875. for (i = 0; i < points.length - 1; i++) {
  54876. points[i + 1].subtractToRef(points[i], curvect);
  54877. nb = Math.floor(curvect.length() / shft);
  54878. curvect.normalize();
  54879. j = 0;
  54880. while (j < nb && p < positions.length) {
  54881. curshft = shft * j;
  54882. positions[p] = points[i].x + curshft * curvect.x;
  54883. positions[p + 1] = points[i].y + curshft * curvect.y;
  54884. positions[p + 2] = points[i].z + curshft * curvect.z;
  54885. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54886. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54887. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54888. p += 6;
  54889. j++;
  54890. }
  54891. }
  54892. while (p < positions.length) {
  54893. positions[p] = points[i].x;
  54894. positions[p + 1] = points[i].y;
  54895. positions[p + 2] = points[i].z;
  54896. p += 3;
  54897. }
  54898. };
  54899. instance.updateMeshPositions(positionFunction, false);
  54900. return instance;
  54901. }
  54902. // dashed lines creation
  54903. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54904. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54905. vertexData.applyToMesh(dashedLines, options.updatable);
  54906. dashedLines.dashSize = dashSize;
  54907. dashedLines.gapSize = gapSize;
  54908. return dashedLines;
  54909. };
  54910. /**
  54911. * Creates an extruded shape mesh.
  54912. * 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.
  54913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54914. *
  54915. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54916. * 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
  54917. * extruded along the Z axis.
  54918. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54919. * 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.
  54920. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54921. * 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
  54922. * 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
  54923. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54925. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  54926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54927. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54929. */
  54930. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54931. if (scene === void 0) { scene = null; }
  54932. var path = options.path;
  54933. var shape = options.shape;
  54934. var scale = options.scale || 1;
  54935. var rotation = options.rotation || 0;
  54936. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54937. var updatable = options.updatable;
  54938. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54939. var instance = options.instance || null;
  54940. var invertUV = options.invertUV || false;
  54941. 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);
  54942. };
  54943. /**
  54944. * Creates an custom extruded shape mesh.
  54945. * 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.
  54946. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54947. *
  54948. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54949. * 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
  54950. * extruded along the Z axis.
  54951. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54952. * 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
  54953. * and the distance of this point from the begining of the path :
  54954. * ```javascript
  54955. * var rotationFunction = function(i, distance) {
  54956. * // do things
  54957. * return rotationValue; }
  54958. * ```
  54959. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54960. * 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
  54961. * and the distance of this point from the begining of the path :
  54962. * ```javascript
  54963. * var scaleFunction = function(i, distance) {
  54964. * // do things
  54965. * return scaleValue;}
  54966. * ```
  54967. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54968. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54969. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54970. * 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
  54971. * 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
  54972. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54973. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54974. * 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).
  54975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54976. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54978. */
  54979. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54980. var path = options.path;
  54981. var shape = options.shape;
  54982. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54983. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54984. var ribbonCloseArray = options.ribbonCloseArray || false;
  54985. var ribbonClosePath = options.ribbonClosePath || false;
  54986. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54987. var updatable = options.updatable;
  54988. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54989. var instance = options.instance;
  54990. var invertUV = options.invertUV || false;
  54991. 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);
  54992. };
  54993. /**
  54994. * Creates lathe mesh.
  54995. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54997. *
  54998. * 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
  54999. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55000. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55001. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55002. * 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.
  55003. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55004. * 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
  55005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55006. * 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).
  55007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55008. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55010. */
  55011. MeshBuilder.CreateLathe = function (name, options, scene) {
  55012. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55013. var closed = (options.closed === undefined) ? true : options.closed;
  55014. var shape = options.shape;
  55015. var radius = options.radius || 1;
  55016. var tessellation = options.tessellation || 64;
  55017. var updatable = options.updatable;
  55018. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55019. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55020. var pi2 = Math.PI * 2;
  55021. var paths = new Array();
  55022. var invertUV = options.invertUV || false;
  55023. var i = 0;
  55024. var p = 0;
  55025. var step = pi2 / tessellation * arc;
  55026. var rotated;
  55027. var path = new Array();
  55028. ;
  55029. for (i = 0; i <= tessellation; i++) {
  55030. var path = [];
  55031. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55032. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55033. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55034. }
  55035. for (p = 0; p < shape.length; p++) {
  55036. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55037. path.push(rotated);
  55038. }
  55039. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55040. 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));
  55041. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55042. }
  55043. paths.push(path);
  55044. }
  55045. // lathe ribbon
  55046. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55047. return lathe;
  55048. };
  55049. /**
  55050. * Creates a plane mesh.
  55051. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55052. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55053. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55054. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55056. * 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).
  55057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55059. */
  55060. MeshBuilder.CreatePlane = function (name, options, scene) {
  55061. var plane = new BABYLON.Mesh(name, scene);
  55062. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55063. plane._originalBuilderSideOrientation = options.sideOrientation;
  55064. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55065. vertexData.applyToMesh(plane, options.updatable);
  55066. if (options.sourcePlane) {
  55067. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55068. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55069. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55070. plane.rotate(vectorProduct, product);
  55071. }
  55072. return plane;
  55073. };
  55074. /**
  55075. * Creates a ground mesh.
  55076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55077. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55078. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55080. */
  55081. MeshBuilder.CreateGround = function (name, options, scene) {
  55082. var ground = new BABYLON.GroundMesh(name, scene);
  55083. ground._setReady(false);
  55084. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55085. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55086. ground._width = options.width || 1;
  55087. ground._height = options.height || 1;
  55088. ground._maxX = ground._width / 2;
  55089. ground._maxZ = ground._height / 2;
  55090. ground._minX = -ground._maxX;
  55091. ground._minZ = -ground._maxZ;
  55092. var vertexData = BABYLON.VertexData.CreateGround(options);
  55093. vertexData.applyToMesh(ground, options.updatable);
  55094. ground._setReady(true);
  55095. return ground;
  55096. };
  55097. /**
  55098. * Creates a tiled ground mesh.
  55099. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55100. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55101. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55102. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55103. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55104. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55105. * numbers of subdivisions on the ground width and height of each tile.
  55106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55107. */
  55108. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55109. var tiledGround = new BABYLON.Mesh(name, scene);
  55110. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55111. vertexData.applyToMesh(tiledGround, options.updatable);
  55112. return tiledGround;
  55113. };
  55114. /**
  55115. * Creates a ground mesh from a height map.
  55116. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55118. * The parameter `url` sets the URL of the height map image resource.
  55119. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55120. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55121. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55122. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55123. * 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.
  55124. * 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).
  55125. * This function is passed the newly built mesh :
  55126. * ```javascript
  55127. * function(mesh) { // do things
  55128. * return; }
  55129. * ```
  55130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55131. */
  55132. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55133. var width = options.width || 10.0;
  55134. var height = options.height || 10.0;
  55135. var subdivisions = options.subdivisions || 1 | 0;
  55136. var minHeight = options.minHeight || 0.0;
  55137. var maxHeight = options.maxHeight || 1.0;
  55138. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55139. var updatable = options.updatable;
  55140. var onReady = options.onReady;
  55141. var ground = new BABYLON.GroundMesh(name, scene);
  55142. ground._subdivisionsX = subdivisions;
  55143. ground._subdivisionsY = subdivisions;
  55144. ground._width = width;
  55145. ground._height = height;
  55146. ground._maxX = ground._width / 2.0;
  55147. ground._maxZ = ground._height / 2.0;
  55148. ground._minX = -ground._maxX;
  55149. ground._minZ = -ground._maxZ;
  55150. ground._setReady(false);
  55151. var onload = function (img) {
  55152. // Getting height map data
  55153. var canvas = document.createElement("canvas");
  55154. var context = canvas.getContext("2d");
  55155. if (!context) {
  55156. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55157. }
  55158. if (scene.isDisposed) {
  55159. return;
  55160. }
  55161. var bufferWidth = img.width;
  55162. var bufferHeight = img.height;
  55163. canvas.width = bufferWidth;
  55164. canvas.height = bufferHeight;
  55165. context.drawImage(img, 0, 0);
  55166. // Create VertexData from map data
  55167. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55168. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55169. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55170. width: width, height: height,
  55171. subdivisions: subdivisions,
  55172. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55173. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55174. });
  55175. vertexData.applyToMesh(ground, updatable);
  55176. ground._setReady(true);
  55177. //execute ready callback, if set
  55178. if (onReady) {
  55179. onReady(ground);
  55180. }
  55181. };
  55182. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55183. return ground;
  55184. };
  55185. /**
  55186. * Creates a polygon mesh.
  55187. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55188. * 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.
  55189. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55191. * 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).
  55192. * Remember you can only change the shape positions, not their number when updating a polygon.
  55193. */
  55194. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55195. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55196. var shape = options.shape;
  55197. var holes = options.holes || [];
  55198. var depth = options.depth || 0;
  55199. var contours = [];
  55200. var hole = [];
  55201. for (var i = 0; i < shape.length; i++) {
  55202. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55203. }
  55204. var epsilon = 0.00000001;
  55205. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55206. contours.pop();
  55207. }
  55208. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55209. for (var hNb = 0; hNb < holes.length; hNb++) {
  55210. hole = [];
  55211. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55212. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55213. }
  55214. polygonTriangulation.addHole(hole);
  55215. }
  55216. var polygon = polygonTriangulation.build(options.updatable, depth);
  55217. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55218. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55219. vertexData.applyToMesh(polygon, options.updatable);
  55220. return polygon;
  55221. };
  55222. ;
  55223. /**
  55224. * Creates an extruded polygon mesh, with depth in the Y direction.
  55225. * 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).
  55226. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55227. */
  55228. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55229. return MeshBuilder.CreatePolygon(name, options, scene);
  55230. };
  55231. ;
  55232. /**
  55233. * Creates a tube mesh.
  55234. * 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.
  55235. *
  55236. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55237. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55238. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55239. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55240. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55241. * 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.
  55242. * It must return a radius value (positive float) :
  55243. * ```javascript
  55244. * var radiusFunction = function(i, distance) {
  55245. * // do things
  55246. * return radius; }
  55247. * ```
  55248. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55249. * 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
  55250. * 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
  55251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55252. * 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).
  55253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55254. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55256. */
  55257. MeshBuilder.CreateTube = function (name, options, scene) {
  55258. var path = options.path;
  55259. var instance = options.instance;
  55260. var radius = 1.0;
  55261. if (instance) {
  55262. radius = instance.radius;
  55263. }
  55264. if (options.radius !== undefined) {
  55265. radius = options.radius;
  55266. }
  55267. ;
  55268. var tessellation = options.tessellation || 64 | 0;
  55269. var radiusFunction = options.radiusFunction || null;
  55270. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55271. var invertUV = options.invertUV || false;
  55272. var updatable = options.updatable;
  55273. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55274. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55275. // tube geometry
  55276. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55277. var tangents = path3D.getTangents();
  55278. var normals = path3D.getNormals();
  55279. var distances = path3D.getDistances();
  55280. var pi2 = Math.PI * 2;
  55281. var step = pi2 / tessellation * arc;
  55282. var returnRadius = function () { return radius; };
  55283. var radiusFunctionFinal = radiusFunction || returnRadius;
  55284. var circlePath;
  55285. var rad;
  55286. var normal;
  55287. var rotated;
  55288. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55289. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55290. for (var i = 0; i < path.length; i++) {
  55291. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55292. circlePath = Array(); // current circle array
  55293. normal = normals[i]; // current normal
  55294. for (var t = 0; t < tessellation; t++) {
  55295. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55296. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55297. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55298. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55299. circlePath[t] = rotated;
  55300. }
  55301. circlePaths[index] = circlePath;
  55302. index++;
  55303. }
  55304. // cap
  55305. var capPath = function (nbPoints, pathIndex) {
  55306. var pointCap = Array();
  55307. for (var i = 0; i < nbPoints; i++) {
  55308. pointCap.push(path[pathIndex]);
  55309. }
  55310. return pointCap;
  55311. };
  55312. switch (cap) {
  55313. case BABYLON.Mesh.NO_CAP:
  55314. break;
  55315. case BABYLON.Mesh.CAP_START:
  55316. circlePaths[0] = capPath(tessellation, 0);
  55317. circlePaths[1] = circlePaths[2].slice(0);
  55318. break;
  55319. case BABYLON.Mesh.CAP_END:
  55320. circlePaths[index] = circlePaths[index - 1].slice(0);
  55321. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55322. break;
  55323. case BABYLON.Mesh.CAP_ALL:
  55324. circlePaths[0] = capPath(tessellation, 0);
  55325. circlePaths[1] = circlePaths[2].slice(0);
  55326. circlePaths[index] = circlePaths[index - 1].slice(0);
  55327. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55328. break;
  55329. default:
  55330. break;
  55331. }
  55332. return circlePaths;
  55333. };
  55334. var path3D;
  55335. var pathArray;
  55336. if (instance) {
  55337. var arc = options.arc || instance.arc;
  55338. path3D = (instance.path3D).update(path);
  55339. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55340. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55341. instance.path3D = path3D;
  55342. instance.pathArray = pathArray;
  55343. instance.arc = arc;
  55344. instance.radius = radius;
  55345. return instance;
  55346. }
  55347. // tube creation
  55348. path3D = new BABYLON.Path3D(path);
  55349. var newPathArray = new Array();
  55350. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55351. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55352. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55353. tube.pathArray = pathArray;
  55354. tube.path3D = path3D;
  55355. tube.tessellation = tessellation;
  55356. tube.cap = cap;
  55357. tube.arc = options.arc;
  55358. tube.radius = radius;
  55359. return tube;
  55360. };
  55361. /**
  55362. * Creates a polyhedron mesh.
  55363. *
  55364. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55365. * 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
  55366. * to choose the wanted type.
  55367. * The parameter `size` (positive float, default 1) sets the polygon size.
  55368. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55369. * 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`.
  55370. * 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
  55371. * 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)`).
  55372. * 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
  55373. * 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.
  55374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55375. * 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).
  55376. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55378. */
  55379. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55380. var polyhedron = new BABYLON.Mesh(name, scene);
  55381. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55382. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55383. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55384. vertexData.applyToMesh(polyhedron, options.updatable);
  55385. return polyhedron;
  55386. };
  55387. /**
  55388. * Creates a decal mesh.
  55389. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55390. * 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.
  55391. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55392. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55393. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55394. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55395. */
  55396. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55397. var indices = sourceMesh.getIndices();
  55398. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55399. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55400. var position = options.position || BABYLON.Vector3.Zero();
  55401. var normal = options.normal || BABYLON.Vector3.Up();
  55402. var size = options.size || BABYLON.Vector3.One();
  55403. var angle = options.angle || 0;
  55404. // Getting correct rotation
  55405. if (!normal) {
  55406. var target = new BABYLON.Vector3(0, 0, 1);
  55407. var camera = sourceMesh.getScene().activeCamera;
  55408. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55409. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55410. }
  55411. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55412. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55413. var pitch = Math.atan2(normal.y, len);
  55414. // Matrix
  55415. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55416. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55417. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55418. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55419. var vertexData = new BABYLON.VertexData();
  55420. vertexData.indices = [];
  55421. vertexData.positions = [];
  55422. vertexData.normals = [];
  55423. vertexData.uvs = [];
  55424. var currentVertexDataIndex = 0;
  55425. var extractDecalVector3 = function (indexId) {
  55426. var result = new BABYLON.PositionNormalVertex();
  55427. if (!indices || !positions || !normals) {
  55428. return result;
  55429. }
  55430. var vertexId = indices[indexId];
  55431. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55432. // Send vector to decal local world
  55433. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55434. // Get normal
  55435. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55436. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55437. return result;
  55438. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55439. var clip = function (vertices, axis) {
  55440. if (vertices.length === 0) {
  55441. return vertices;
  55442. }
  55443. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55444. var clipVertices = function (v0, v1) {
  55445. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55446. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55447. };
  55448. var result = new Array();
  55449. for (var index = 0; index < vertices.length; index += 3) {
  55450. var v1Out;
  55451. var v2Out;
  55452. var v3Out;
  55453. var total = 0;
  55454. var nV1 = null;
  55455. var nV2 = null;
  55456. var nV3 = null;
  55457. var nV4 = null;
  55458. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55459. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55460. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55461. v1Out = d1 > 0;
  55462. v2Out = d2 > 0;
  55463. v3Out = d3 > 0;
  55464. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55465. switch (total) {
  55466. case 0:
  55467. result.push(vertices[index]);
  55468. result.push(vertices[index + 1]);
  55469. result.push(vertices[index + 2]);
  55470. break;
  55471. case 1:
  55472. if (v1Out) {
  55473. nV1 = vertices[index + 1];
  55474. nV2 = vertices[index + 2];
  55475. nV3 = clipVertices(vertices[index], nV1);
  55476. nV4 = clipVertices(vertices[index], nV2);
  55477. }
  55478. if (v2Out) {
  55479. nV1 = vertices[index];
  55480. nV2 = vertices[index + 2];
  55481. nV3 = clipVertices(vertices[index + 1], nV1);
  55482. nV4 = clipVertices(vertices[index + 1], nV2);
  55483. result.push(nV3);
  55484. result.push(nV2.clone());
  55485. result.push(nV1.clone());
  55486. result.push(nV2.clone());
  55487. result.push(nV3.clone());
  55488. result.push(nV4);
  55489. break;
  55490. }
  55491. if (v3Out) {
  55492. nV1 = vertices[index];
  55493. nV2 = vertices[index + 1];
  55494. nV3 = clipVertices(vertices[index + 2], nV1);
  55495. nV4 = clipVertices(vertices[index + 2], nV2);
  55496. }
  55497. if (nV1 && nV2 && nV3 && nV4) {
  55498. result.push(nV1.clone());
  55499. result.push(nV2.clone());
  55500. result.push(nV3);
  55501. result.push(nV4);
  55502. result.push(nV3.clone());
  55503. result.push(nV2.clone());
  55504. }
  55505. break;
  55506. case 2:
  55507. if (!v1Out) {
  55508. nV1 = vertices[index].clone();
  55509. nV2 = clipVertices(nV1, vertices[index + 1]);
  55510. nV3 = clipVertices(nV1, vertices[index + 2]);
  55511. result.push(nV1);
  55512. result.push(nV2);
  55513. result.push(nV3);
  55514. }
  55515. if (!v2Out) {
  55516. nV1 = vertices[index + 1].clone();
  55517. nV2 = clipVertices(nV1, vertices[index + 2]);
  55518. nV3 = clipVertices(nV1, vertices[index]);
  55519. result.push(nV1);
  55520. result.push(nV2);
  55521. result.push(nV3);
  55522. }
  55523. if (!v3Out) {
  55524. nV1 = vertices[index + 2].clone();
  55525. nV2 = clipVertices(nV1, vertices[index]);
  55526. nV3 = clipVertices(nV1, vertices[index + 1]);
  55527. result.push(nV1);
  55528. result.push(nV2);
  55529. result.push(nV3);
  55530. }
  55531. break;
  55532. case 3:
  55533. break;
  55534. }
  55535. }
  55536. return result;
  55537. };
  55538. for (var index = 0; index < indices.length; index += 3) {
  55539. var faceVertices = new Array();
  55540. faceVertices.push(extractDecalVector3(index));
  55541. faceVertices.push(extractDecalVector3(index + 1));
  55542. faceVertices.push(extractDecalVector3(index + 2));
  55543. // Clip
  55544. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55545. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55546. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55547. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55548. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55549. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55550. if (faceVertices.length === 0) {
  55551. continue;
  55552. }
  55553. // Add UVs and get back to world
  55554. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55555. var vertex = faceVertices[vIndex];
  55556. //TODO check for Int32Array | Uint32Array | Uint16Array
  55557. vertexData.indices.push(currentVertexDataIndex);
  55558. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55559. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55560. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55561. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55562. currentVertexDataIndex++;
  55563. }
  55564. }
  55565. // Return mesh
  55566. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55567. vertexData.applyToMesh(decal);
  55568. decal.position = position.clone();
  55569. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55570. return decal;
  55571. };
  55572. // Privates
  55573. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55574. // extrusion geometry
  55575. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55576. var tangents = path3D.getTangents();
  55577. var normals = path3D.getNormals();
  55578. var binormals = path3D.getBinormals();
  55579. var distances = path3D.getDistances();
  55580. var angle = 0;
  55581. var returnScale = function () { return scale !== null ? scale : 1; };
  55582. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55583. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55584. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55585. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55586. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55587. for (var i = 0; i < curve.length; i++) {
  55588. var shapePath = new Array();
  55589. var angleStep = rotate(i, distances[i]);
  55590. var scaleRatio = scl(i, distances[i]);
  55591. for (var p = 0; p < shape.length; p++) {
  55592. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55593. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55594. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55595. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55596. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55597. shapePath[p] = rotated;
  55598. }
  55599. shapePaths[index] = shapePath;
  55600. angle += angleStep;
  55601. index++;
  55602. }
  55603. // cap
  55604. var capPath = function (shapePath) {
  55605. var pointCap = Array();
  55606. var barycenter = BABYLON.Vector3.Zero();
  55607. var i;
  55608. for (i = 0; i < shapePath.length; i++) {
  55609. barycenter.addInPlace(shapePath[i]);
  55610. }
  55611. barycenter.scaleInPlace(1.0 / shapePath.length);
  55612. for (i = 0; i < shapePath.length; i++) {
  55613. pointCap.push(barycenter);
  55614. }
  55615. return pointCap;
  55616. };
  55617. switch (cap) {
  55618. case BABYLON.Mesh.NO_CAP:
  55619. break;
  55620. case BABYLON.Mesh.CAP_START:
  55621. shapePaths[0] = capPath(shapePaths[2]);
  55622. shapePaths[1] = shapePaths[2];
  55623. break;
  55624. case BABYLON.Mesh.CAP_END:
  55625. shapePaths[index] = shapePaths[index - 1];
  55626. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55627. break;
  55628. case BABYLON.Mesh.CAP_ALL:
  55629. shapePaths[0] = capPath(shapePaths[2]);
  55630. shapePaths[1] = shapePaths[2];
  55631. shapePaths[index] = shapePaths[index - 1];
  55632. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55633. break;
  55634. default:
  55635. break;
  55636. }
  55637. return shapePaths;
  55638. };
  55639. var path3D;
  55640. var pathArray;
  55641. if (instance) {
  55642. path3D = (instance.path3D).update(curve);
  55643. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55644. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55645. return instance;
  55646. }
  55647. // extruded shape creation
  55648. path3D = new BABYLON.Path3D(curve);
  55649. var newShapePaths = new Array();
  55650. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55651. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55652. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55653. extrudedGeneric.pathArray = pathArray;
  55654. extrudedGeneric.path3D = path3D;
  55655. extrudedGeneric.cap = cap;
  55656. return extrudedGeneric;
  55657. };
  55658. return MeshBuilder;
  55659. }());
  55660. BABYLON.MeshBuilder = MeshBuilder;
  55661. })(BABYLON || (BABYLON = {}));
  55662. //# sourceMappingURL=babylon.meshBuilder.js.map
  55663. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  55664. var BABYLON;
  55665. (function (BABYLON) {
  55666. /**
  55667. * Draco compression (https://google.github.io/draco/)
  55668. */
  55669. var DracoCompression = /** @class */ (function () {
  55670. /**
  55671. * Constructor
  55672. * @param numWorkers The number of workers for async operations
  55673. */
  55674. function DracoCompression(numWorkers) {
  55675. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55676. var workers = new Array(numWorkers);
  55677. for (var i = 0; i < workers.length; i++) {
  55678. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  55679. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55680. workers[i] = worker;
  55681. }
  55682. this._workerPool = new BABYLON.WorkerPool(workers);
  55683. }
  55684. /**
  55685. * Stop all async operations and release resources.
  55686. */
  55687. DracoCompression.prototype.dispose = function () {
  55688. this._workerPool.dispose();
  55689. delete this._workerPool;
  55690. };
  55691. /**
  55692. * Decode Draco compressed mesh data to vertex data.
  55693. * @param data The array buffer view for the Draco compression data
  55694. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55695. * @returns A promise that resolves with the decoded vertex data
  55696. */
  55697. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55698. var _this = this;
  55699. return new Promise(function (resolve, reject) {
  55700. _this._workerPool.push(function (worker, onComplete) {
  55701. var vertexData = new BABYLON.VertexData();
  55702. var onError = function (error) {
  55703. worker.removeEventListener("error", onError);
  55704. worker.removeEventListener("message", onMessage);
  55705. reject(error);
  55706. onComplete();
  55707. };
  55708. var onMessage = function (message) {
  55709. if (message.data === "done") {
  55710. worker.removeEventListener("error", onError);
  55711. worker.removeEventListener("message", onMessage);
  55712. resolve(vertexData);
  55713. onComplete();
  55714. }
  55715. else if (message.data.id === "indices") {
  55716. vertexData.indices = message.data.value;
  55717. }
  55718. else {
  55719. vertexData.set(message.data.value, message.data.id);
  55720. }
  55721. };
  55722. worker.addEventListener("error", onError);
  55723. worker.addEventListener("message", onMessage);
  55724. var dataCopy = new Uint8Array(data.byteLength);
  55725. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55726. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55727. });
  55728. });
  55729. };
  55730. /**
  55731. * The worker function that gets converted to a blob url to pass into a worker.
  55732. */
  55733. DracoCompression._Worker = function () {
  55734. // self is actually a DedicatedWorkerGlobalScope
  55735. var _self = self;
  55736. var decodeMesh = function (data, attributes) {
  55737. var dracoModule = new DracoDecoderModule();
  55738. var buffer = new dracoModule.DecoderBuffer();
  55739. buffer.Init(data, data.byteLength);
  55740. var decoder = new dracoModule.Decoder();
  55741. var geometry;
  55742. var status;
  55743. try {
  55744. var type = decoder.GetEncodedGeometryType(buffer);
  55745. switch (type) {
  55746. case dracoModule.TRIANGULAR_MESH:
  55747. geometry = new dracoModule.Mesh();
  55748. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55749. break;
  55750. case dracoModule.POINT_CLOUD:
  55751. geometry = new dracoModule.PointCloud();
  55752. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55753. break;
  55754. default:
  55755. throw new Error("Invalid geometry type " + type);
  55756. }
  55757. if (!status.ok() || !geometry.ptr) {
  55758. throw new Error(status.error_msg());
  55759. }
  55760. var numPoints = geometry.num_points();
  55761. if (type === dracoModule.TRIANGULAR_MESH) {
  55762. var numFaces = geometry.num_faces();
  55763. var faceIndices = new dracoModule.DracoInt32Array();
  55764. try {
  55765. var indices = new Uint32Array(numFaces * 3);
  55766. for (var i = 0; i < numFaces; i++) {
  55767. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55768. var offset = i * 3;
  55769. indices[offset + 0] = faceIndices.GetValue(0);
  55770. indices[offset + 1] = faceIndices.GetValue(1);
  55771. indices[offset + 2] = faceIndices.GetValue(2);
  55772. }
  55773. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55774. }
  55775. finally {
  55776. dracoModule.destroy(faceIndices);
  55777. }
  55778. }
  55779. for (var kind in attributes) {
  55780. var uniqueId = attributes[kind];
  55781. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55782. var dracoData = new dracoModule.DracoFloat32Array();
  55783. try {
  55784. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55785. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55786. for (var i = 0; i < babylonData.length; i++) {
  55787. babylonData[i] = dracoData.GetValue(i);
  55788. }
  55789. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55790. }
  55791. finally {
  55792. dracoModule.destroy(dracoData);
  55793. }
  55794. }
  55795. }
  55796. finally {
  55797. if (geometry) {
  55798. dracoModule.destroy(geometry);
  55799. }
  55800. dracoModule.destroy(decoder);
  55801. dracoModule.destroy(buffer);
  55802. }
  55803. _self.postMessage("done");
  55804. };
  55805. _self.onmessage = function (event) {
  55806. switch (event.data.id) {
  55807. case "initDecoder": {
  55808. importScripts(event.data.url);
  55809. break;
  55810. }
  55811. case "decodeMesh": {
  55812. decodeMesh(event.data.data, event.data.attributes);
  55813. break;
  55814. }
  55815. }
  55816. };
  55817. };
  55818. DracoCompression._GetDefaultDecoderUrl = function () {
  55819. for (var i = 0; i < document.scripts.length; i++) {
  55820. if (document.scripts[i].type === "text/x-draco-decoder") {
  55821. return document.scripts[i].src;
  55822. }
  55823. }
  55824. return null;
  55825. };
  55826. /**
  55827. * Gets the url to the draco decoder if available.
  55828. */
  55829. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  55830. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55831. return DracoCompression;
  55832. }());
  55833. BABYLON.DracoCompression = DracoCompression;
  55834. })(BABYLON || (BABYLON = {}));
  55835. //# sourceMappingURL=babylon.dracoCompression.js.map
  55836. var BABYLON;
  55837. (function (BABYLON) {
  55838. var AudioEngine = /** @class */ (function () {
  55839. function AudioEngine() {
  55840. this._audioContext = null;
  55841. this._audioContextInitialized = false;
  55842. this.canUseWebAudio = false;
  55843. this.WarnedWebAudioUnsupported = false;
  55844. this.unlocked = false;
  55845. this.isMP3supported = false;
  55846. this.isOGGsupported = false;
  55847. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55848. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55849. this.canUseWebAudio = true;
  55850. }
  55851. var audioElem = document.createElement('audio');
  55852. try {
  55853. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55854. this.isMP3supported = true;
  55855. }
  55856. }
  55857. catch (e) {
  55858. // protect error during capability check.
  55859. }
  55860. try {
  55861. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55862. this.isOGGsupported = true;
  55863. }
  55864. }
  55865. catch (e) {
  55866. // protect error during capability check.
  55867. }
  55868. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55869. this._unlockiOSaudio();
  55870. }
  55871. else {
  55872. this.unlocked = true;
  55873. }
  55874. }
  55875. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55876. get: function () {
  55877. if (!this._audioContextInitialized) {
  55878. this._initializeAudioContext();
  55879. }
  55880. return this._audioContext;
  55881. },
  55882. enumerable: true,
  55883. configurable: true
  55884. });
  55885. AudioEngine.prototype._unlockiOSaudio = function () {
  55886. var _this = this;
  55887. var unlockaudio = function () {
  55888. if (!_this.audioContext) {
  55889. return;
  55890. }
  55891. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55892. var source = _this.audioContext.createBufferSource();
  55893. source.buffer = buffer;
  55894. source.connect(_this.audioContext.destination);
  55895. source.start(0);
  55896. setTimeout(function () {
  55897. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55898. _this.unlocked = true;
  55899. window.removeEventListener('touchend', unlockaudio, false);
  55900. if (_this.onAudioUnlocked) {
  55901. _this.onAudioUnlocked();
  55902. }
  55903. }
  55904. }, 0);
  55905. };
  55906. window.addEventListener('touchend', unlockaudio, false);
  55907. };
  55908. AudioEngine.prototype._initializeAudioContext = function () {
  55909. try {
  55910. if (this.canUseWebAudio) {
  55911. this._audioContext = new AudioContext();
  55912. // create a global volume gain node
  55913. this.masterGain = this._audioContext.createGain();
  55914. this.masterGain.gain.value = 1;
  55915. this.masterGain.connect(this._audioContext.destination);
  55916. this._audioContextInitialized = true;
  55917. }
  55918. }
  55919. catch (e) {
  55920. this.canUseWebAudio = false;
  55921. BABYLON.Tools.Error("Web Audio: " + e.message);
  55922. }
  55923. };
  55924. AudioEngine.prototype.dispose = function () {
  55925. if (this.canUseWebAudio && this._audioContextInitialized) {
  55926. if (this._connectedAnalyser && this._audioContext) {
  55927. this._connectedAnalyser.stopDebugCanvas();
  55928. this._connectedAnalyser.dispose();
  55929. this.masterGain.disconnect();
  55930. this.masterGain.connect(this._audioContext.destination);
  55931. this._connectedAnalyser = null;
  55932. }
  55933. this.masterGain.gain.value = 1;
  55934. }
  55935. this.WarnedWebAudioUnsupported = false;
  55936. };
  55937. AudioEngine.prototype.getGlobalVolume = function () {
  55938. if (this.canUseWebAudio && this._audioContextInitialized) {
  55939. return this.masterGain.gain.value;
  55940. }
  55941. else {
  55942. return -1;
  55943. }
  55944. };
  55945. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55946. if (this.canUseWebAudio && this._audioContextInitialized) {
  55947. this.masterGain.gain.value = newVolume;
  55948. }
  55949. };
  55950. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55951. if (this._connectedAnalyser) {
  55952. this._connectedAnalyser.stopDebugCanvas();
  55953. }
  55954. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55955. this._connectedAnalyser = analyser;
  55956. this.masterGain.disconnect();
  55957. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55958. }
  55959. };
  55960. return AudioEngine;
  55961. }());
  55962. BABYLON.AudioEngine = AudioEngine;
  55963. })(BABYLON || (BABYLON = {}));
  55964. //# sourceMappingURL=babylon.audioEngine.js.map
  55965. var BABYLON;
  55966. (function (BABYLON) {
  55967. var Sound = /** @class */ (function () {
  55968. /**
  55969. * Create a sound and attach it to a scene
  55970. * @param name Name of your sound
  55971. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55972. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55973. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55974. */
  55975. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55976. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55977. var _this = this;
  55978. this.autoplay = false;
  55979. this.loop = false;
  55980. this.useCustomAttenuation = false;
  55981. this.spatialSound = false;
  55982. this.refDistance = 1;
  55983. this.rolloffFactor = 1;
  55984. this.maxDistance = 100;
  55985. this.distanceModel = "linear";
  55986. this._panningModel = "equalpower";
  55987. this._playbackRate = 1;
  55988. this._streaming = false;
  55989. this._startTime = 0;
  55990. this._startOffset = 0;
  55991. this._position = BABYLON.Vector3.Zero();
  55992. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55993. this._volume = 1;
  55994. this._isReadyToPlay = false;
  55995. this.isPlaying = false;
  55996. this.isPaused = false;
  55997. this._isDirectional = false;
  55998. // Used if you'd like to create a directional sound.
  55999. // If not set, the sound will be omnidirectional
  56000. this._coneInnerAngle = 360;
  56001. this._coneOuterAngle = 360;
  56002. this._coneOuterGain = 0;
  56003. this._isOutputConnected = false;
  56004. this._urlType = "Unknown";
  56005. this.name = name;
  56006. this._scene = scene;
  56007. this._readyToPlayCallback = readyToPlayCallback;
  56008. // Default custom attenuation function is a linear attenuation
  56009. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56010. if (currentDistance < maxDistance) {
  56011. return currentVolume * (1 - currentDistance / maxDistance);
  56012. }
  56013. else {
  56014. return 0;
  56015. }
  56016. };
  56017. if (options) {
  56018. this.autoplay = options.autoplay || false;
  56019. this.loop = options.loop || false;
  56020. // if volume === 0, we need another way to check this option
  56021. if (options.volume !== undefined) {
  56022. this._volume = options.volume;
  56023. }
  56024. this.spatialSound = options.spatialSound || false;
  56025. this.maxDistance = options.maxDistance || 100;
  56026. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56027. this.rolloffFactor = options.rolloffFactor || 1;
  56028. this.refDistance = options.refDistance || 1;
  56029. this.distanceModel = options.distanceModel || "linear";
  56030. this._playbackRate = options.playbackRate || 1;
  56031. this._streaming = options.streaming || false;
  56032. }
  56033. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56034. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56035. this._soundGain.gain.value = this._volume;
  56036. this._inputAudioNode = this._soundGain;
  56037. this._ouputAudioNode = this._soundGain;
  56038. if (this.spatialSound) {
  56039. this._createSpatialParameters();
  56040. }
  56041. this._scene.mainSoundTrack.AddSound(this);
  56042. var validParameter = true;
  56043. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56044. if (urlOrArrayBuffer) {
  56045. if (typeof (urlOrArrayBuffer) === "string")
  56046. this._urlType = "String";
  56047. if (Array.isArray(urlOrArrayBuffer))
  56048. this._urlType = "Array";
  56049. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56050. this._urlType = "ArrayBuffer";
  56051. var urls = [];
  56052. var codecSupportedFound = false;
  56053. switch (this._urlType) {
  56054. case "ArrayBuffer":
  56055. if (urlOrArrayBuffer.byteLength > 0) {
  56056. codecSupportedFound = true;
  56057. this._soundLoaded(urlOrArrayBuffer);
  56058. }
  56059. break;
  56060. case "String":
  56061. urls.push(urlOrArrayBuffer);
  56062. case "Array":
  56063. if (urls.length === 0)
  56064. urls = urlOrArrayBuffer;
  56065. // If we found a supported format, we load it immediately and stop the loop
  56066. for (var i = 0; i < urls.length; i++) {
  56067. var url = urls[i];
  56068. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56069. codecSupportedFound = true;
  56070. }
  56071. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56072. codecSupportedFound = true;
  56073. }
  56074. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56075. codecSupportedFound = true;
  56076. }
  56077. if (url.indexOf("blob:") !== -1) {
  56078. codecSupportedFound = true;
  56079. }
  56080. if (codecSupportedFound) {
  56081. // Loading sound using XHR2
  56082. if (!this._streaming) {
  56083. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56084. }
  56085. else {
  56086. this._htmlAudioElement = new Audio(url);
  56087. this._htmlAudioElement.controls = false;
  56088. this._htmlAudioElement.loop = this.loop;
  56089. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56090. this._htmlAudioElement.preload = "auto";
  56091. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56092. _this._isReadyToPlay = true;
  56093. if (_this.autoplay) {
  56094. _this.play();
  56095. }
  56096. if (_this._readyToPlayCallback) {
  56097. _this._readyToPlayCallback();
  56098. }
  56099. });
  56100. document.body.appendChild(this._htmlAudioElement);
  56101. }
  56102. break;
  56103. }
  56104. }
  56105. break;
  56106. default:
  56107. validParameter = false;
  56108. break;
  56109. }
  56110. if (!validParameter) {
  56111. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56112. }
  56113. else {
  56114. if (!codecSupportedFound) {
  56115. this._isReadyToPlay = true;
  56116. // Simulating a ready to play event to avoid breaking code path
  56117. if (this._readyToPlayCallback) {
  56118. window.setTimeout(function () {
  56119. if (_this._readyToPlayCallback) {
  56120. _this._readyToPlayCallback();
  56121. }
  56122. }, 1000);
  56123. }
  56124. }
  56125. }
  56126. }
  56127. }
  56128. else {
  56129. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56130. this._scene.mainSoundTrack.AddSound(this);
  56131. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56132. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56133. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56134. }
  56135. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56136. if (this._readyToPlayCallback) {
  56137. window.setTimeout(function () {
  56138. if (_this._readyToPlayCallback) {
  56139. _this._readyToPlayCallback();
  56140. }
  56141. }, 1000);
  56142. }
  56143. }
  56144. }
  56145. Sound.prototype.dispose = function () {
  56146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56147. if (this.isPlaying) {
  56148. this.stop();
  56149. }
  56150. this._isReadyToPlay = false;
  56151. if (this.soundTrackId === -1) {
  56152. this._scene.mainSoundTrack.RemoveSound(this);
  56153. }
  56154. else {
  56155. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56156. }
  56157. if (this._soundGain) {
  56158. this._soundGain.disconnect();
  56159. this._soundGain = null;
  56160. }
  56161. if (this._soundPanner) {
  56162. this._soundPanner.disconnect();
  56163. this._soundPanner = null;
  56164. }
  56165. if (this._soundSource) {
  56166. this._soundSource.disconnect();
  56167. this._soundSource = null;
  56168. }
  56169. this._audioBuffer = null;
  56170. if (this._htmlAudioElement) {
  56171. this._htmlAudioElement.pause();
  56172. this._htmlAudioElement.src = "";
  56173. document.body.removeChild(this._htmlAudioElement);
  56174. }
  56175. if (this._connectedMesh && this._registerFunc) {
  56176. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56177. this._connectedMesh = null;
  56178. }
  56179. }
  56180. };
  56181. Sound.prototype.isReady = function () {
  56182. return this._isReadyToPlay;
  56183. };
  56184. Sound.prototype._soundLoaded = function (audioData) {
  56185. var _this = this;
  56186. if (!BABYLON.Engine.audioEngine.audioContext) {
  56187. return;
  56188. }
  56189. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56190. _this._audioBuffer = buffer;
  56191. _this._isReadyToPlay = true;
  56192. if (_this.autoplay) {
  56193. _this.play();
  56194. }
  56195. if (_this._readyToPlayCallback) {
  56196. _this._readyToPlayCallback();
  56197. }
  56198. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56199. };
  56200. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56201. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56202. this._audioBuffer = audioBuffer;
  56203. this._isReadyToPlay = true;
  56204. }
  56205. };
  56206. Sound.prototype.updateOptions = function (options) {
  56207. if (options) {
  56208. this.loop = options.loop || this.loop;
  56209. this.maxDistance = options.maxDistance || this.maxDistance;
  56210. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56211. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56212. this.refDistance = options.refDistance || this.refDistance;
  56213. this.distanceModel = options.distanceModel || this.distanceModel;
  56214. this._playbackRate = options.playbackRate || this._playbackRate;
  56215. this._updateSpatialParameters();
  56216. if (this.isPlaying) {
  56217. if (this._streaming) {
  56218. this._htmlAudioElement.playbackRate = this._playbackRate;
  56219. }
  56220. else {
  56221. if (this._soundSource) {
  56222. this._soundSource.playbackRate.value = this._playbackRate;
  56223. }
  56224. }
  56225. }
  56226. }
  56227. };
  56228. Sound.prototype._createSpatialParameters = function () {
  56229. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56230. if (this._scene.headphone) {
  56231. this._panningModel = "HRTF";
  56232. }
  56233. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56234. this._updateSpatialParameters();
  56235. this._soundPanner.connect(this._ouputAudioNode);
  56236. this._inputAudioNode = this._soundPanner;
  56237. }
  56238. };
  56239. Sound.prototype._updateSpatialParameters = function () {
  56240. if (this.spatialSound && this._soundPanner) {
  56241. if (this.useCustomAttenuation) {
  56242. // Tricks to disable in a way embedded Web Audio attenuation
  56243. this._soundPanner.distanceModel = "linear";
  56244. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56245. this._soundPanner.refDistance = 1;
  56246. this._soundPanner.rolloffFactor = 1;
  56247. this._soundPanner.panningModel = this._panningModel;
  56248. }
  56249. else {
  56250. this._soundPanner.distanceModel = this.distanceModel;
  56251. this._soundPanner.maxDistance = this.maxDistance;
  56252. this._soundPanner.refDistance = this.refDistance;
  56253. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56254. this._soundPanner.panningModel = this._panningModel;
  56255. }
  56256. }
  56257. };
  56258. Sound.prototype.switchPanningModelToHRTF = function () {
  56259. this._panningModel = "HRTF";
  56260. this._switchPanningModel();
  56261. };
  56262. Sound.prototype.switchPanningModelToEqualPower = function () {
  56263. this._panningModel = "equalpower";
  56264. this._switchPanningModel();
  56265. };
  56266. Sound.prototype._switchPanningModel = function () {
  56267. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56268. this._soundPanner.panningModel = this._panningModel;
  56269. }
  56270. };
  56271. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56272. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56273. if (this._isOutputConnected) {
  56274. this._ouputAudioNode.disconnect();
  56275. }
  56276. this._ouputAudioNode.connect(soundTrackAudioNode);
  56277. this._isOutputConnected = true;
  56278. }
  56279. };
  56280. /**
  56281. * Transform this sound into a directional source
  56282. * @param coneInnerAngle Size of the inner cone in degree
  56283. * @param coneOuterAngle Size of the outer cone in degree
  56284. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56285. */
  56286. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56287. if (coneOuterAngle < coneInnerAngle) {
  56288. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56289. return;
  56290. }
  56291. this._coneInnerAngle = coneInnerAngle;
  56292. this._coneOuterAngle = coneOuterAngle;
  56293. this._coneOuterGain = coneOuterGain;
  56294. this._isDirectional = true;
  56295. if (this.isPlaying && this.loop) {
  56296. this.stop();
  56297. this.play();
  56298. }
  56299. };
  56300. Sound.prototype.setPosition = function (newPosition) {
  56301. this._position = newPosition;
  56302. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56303. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56304. }
  56305. };
  56306. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56307. this._localDirection = newLocalDirection;
  56308. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56309. this._updateDirection();
  56310. }
  56311. };
  56312. Sound.prototype._updateDirection = function () {
  56313. if (!this._connectedMesh || !this._soundPanner) {
  56314. return;
  56315. }
  56316. var mat = this._connectedMesh.getWorldMatrix();
  56317. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56318. direction.normalize();
  56319. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56320. };
  56321. Sound.prototype.updateDistanceFromListener = function () {
  56322. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56323. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56324. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56325. }
  56326. };
  56327. Sound.prototype.setAttenuationFunction = function (callback) {
  56328. this._customAttenuationFunction = callback;
  56329. };
  56330. /**
  56331. * Play the sound
  56332. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56333. * @param offset (optional) Start the sound setting it at a specific time
  56334. */
  56335. Sound.prototype.play = function (time, offset) {
  56336. var _this = this;
  56337. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56338. try {
  56339. if (this._startOffset < 0) {
  56340. time = -this._startOffset;
  56341. this._startOffset = 0;
  56342. }
  56343. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56344. if (!this._soundSource || !this._streamingSource) {
  56345. if (this.spatialSound && this._soundPanner) {
  56346. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56347. if (this._isDirectional) {
  56348. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56349. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56350. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56351. if (this._connectedMesh) {
  56352. this._updateDirection();
  56353. }
  56354. else {
  56355. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56356. }
  56357. }
  56358. }
  56359. }
  56360. if (this._streaming) {
  56361. if (!this._streamingSource) {
  56362. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56363. this._htmlAudioElement.onended = function () { _this._onended(); };
  56364. this._htmlAudioElement.playbackRate = this._playbackRate;
  56365. }
  56366. this._streamingSource.disconnect();
  56367. this._streamingSource.connect(this._inputAudioNode);
  56368. this._htmlAudioElement.play();
  56369. }
  56370. else {
  56371. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56372. this._soundSource.buffer = this._audioBuffer;
  56373. this._soundSource.connect(this._inputAudioNode);
  56374. this._soundSource.loop = this.loop;
  56375. this._soundSource.playbackRate.value = this._playbackRate;
  56376. this._soundSource.onended = function () { _this._onended(); };
  56377. if (this._soundSource.buffer) {
  56378. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56379. }
  56380. }
  56381. this._startTime = startTime;
  56382. this.isPlaying = true;
  56383. this.isPaused = false;
  56384. }
  56385. catch (ex) {
  56386. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56387. }
  56388. }
  56389. };
  56390. Sound.prototype._onended = function () {
  56391. this.isPlaying = false;
  56392. if (this.onended) {
  56393. this.onended();
  56394. }
  56395. };
  56396. /**
  56397. * Stop the sound
  56398. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56399. */
  56400. Sound.prototype.stop = function (time) {
  56401. if (this.isPlaying) {
  56402. if (this._streaming) {
  56403. this._htmlAudioElement.pause();
  56404. // Test needed for Firefox or it will generate an Invalid State Error
  56405. if (this._htmlAudioElement.currentTime > 0) {
  56406. this._htmlAudioElement.currentTime = 0;
  56407. }
  56408. }
  56409. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56410. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56411. this._soundSource.stop(stopTime);
  56412. this._soundSource.onended = function () { };
  56413. if (!this.isPaused) {
  56414. this._startOffset = 0;
  56415. }
  56416. }
  56417. this.isPlaying = false;
  56418. }
  56419. };
  56420. Sound.prototype.pause = function () {
  56421. if (this.isPlaying) {
  56422. this.isPaused = true;
  56423. if (this._streaming) {
  56424. this._htmlAudioElement.pause();
  56425. }
  56426. else if (BABYLON.Engine.audioEngine.audioContext) {
  56427. this.stop(0);
  56428. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56429. }
  56430. }
  56431. };
  56432. Sound.prototype.setVolume = function (newVolume, time) {
  56433. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56434. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56435. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56436. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56437. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56438. }
  56439. else {
  56440. this._soundGain.gain.value = newVolume;
  56441. }
  56442. }
  56443. this._volume = newVolume;
  56444. };
  56445. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56446. this._playbackRate = newPlaybackRate;
  56447. if (this.isPlaying) {
  56448. if (this._streaming) {
  56449. this._htmlAudioElement.playbackRate = this._playbackRate;
  56450. }
  56451. else if (this._soundSource) {
  56452. this._soundSource.playbackRate.value = this._playbackRate;
  56453. }
  56454. }
  56455. };
  56456. Sound.prototype.getVolume = function () {
  56457. return this._volume;
  56458. };
  56459. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56460. var _this = this;
  56461. if (this._connectedMesh && this._registerFunc) {
  56462. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56463. this._registerFunc = null;
  56464. }
  56465. this._connectedMesh = meshToConnectTo;
  56466. if (!this.spatialSound) {
  56467. this.spatialSound = true;
  56468. this._createSpatialParameters();
  56469. if (this.isPlaying && this.loop) {
  56470. this.stop();
  56471. this.play();
  56472. }
  56473. }
  56474. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56475. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56476. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56477. };
  56478. Sound.prototype.detachFromMesh = function () {
  56479. if (this._connectedMesh && this._registerFunc) {
  56480. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56481. this._registerFunc = null;
  56482. this._connectedMesh = null;
  56483. }
  56484. };
  56485. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56486. if (!node.getBoundingInfo) {
  56487. return;
  56488. }
  56489. var mesh = node;
  56490. var boundingInfo = mesh.getBoundingInfo();
  56491. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56492. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56493. this._updateDirection();
  56494. }
  56495. };
  56496. Sound.prototype.clone = function () {
  56497. var _this = this;
  56498. if (!this._streaming) {
  56499. var setBufferAndRun = function () {
  56500. if (_this._isReadyToPlay) {
  56501. clonedSound._audioBuffer = _this.getAudioBuffer();
  56502. clonedSound._isReadyToPlay = true;
  56503. if (clonedSound.autoplay) {
  56504. clonedSound.play();
  56505. }
  56506. }
  56507. else {
  56508. window.setTimeout(setBufferAndRun, 300);
  56509. }
  56510. };
  56511. var currentOptions = {
  56512. autoplay: this.autoplay, loop: this.loop,
  56513. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56514. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56515. refDistance: this.refDistance, distanceModel: this.distanceModel
  56516. };
  56517. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56518. if (this.useCustomAttenuation) {
  56519. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56520. }
  56521. clonedSound.setPosition(this._position);
  56522. clonedSound.setPlaybackRate(this._playbackRate);
  56523. setBufferAndRun();
  56524. return clonedSound;
  56525. }
  56526. else {
  56527. return null;
  56528. }
  56529. };
  56530. Sound.prototype.getAudioBuffer = function () {
  56531. return this._audioBuffer;
  56532. };
  56533. Sound.prototype.serialize = function () {
  56534. var serializationObject = {
  56535. name: this.name,
  56536. url: this.name,
  56537. autoplay: this.autoplay,
  56538. loop: this.loop,
  56539. volume: this._volume,
  56540. spatialSound: this.spatialSound,
  56541. maxDistance: this.maxDistance,
  56542. rolloffFactor: this.rolloffFactor,
  56543. refDistance: this.refDistance,
  56544. distanceModel: this.distanceModel,
  56545. playbackRate: this._playbackRate,
  56546. panningModel: this._panningModel,
  56547. soundTrackId: this.soundTrackId
  56548. };
  56549. if (this.spatialSound) {
  56550. if (this._connectedMesh)
  56551. serializationObject.connectedMeshId = this._connectedMesh.id;
  56552. serializationObject.position = this._position.asArray();
  56553. serializationObject.refDistance = this.refDistance;
  56554. serializationObject.distanceModel = this.distanceModel;
  56555. serializationObject.isDirectional = this._isDirectional;
  56556. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56557. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56558. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56559. serializationObject.coneOuterGain = this._coneOuterGain;
  56560. }
  56561. return serializationObject;
  56562. };
  56563. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56564. var soundName = parsedSound.name;
  56565. var soundUrl;
  56566. if (parsedSound.url) {
  56567. soundUrl = rootUrl + parsedSound.url;
  56568. }
  56569. else {
  56570. soundUrl = rootUrl + soundName;
  56571. }
  56572. var options = {
  56573. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56574. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56575. rolloffFactor: parsedSound.rolloffFactor,
  56576. refDistance: parsedSound.refDistance,
  56577. distanceModel: parsedSound.distanceModel,
  56578. playbackRate: parsedSound.playbackRate
  56579. };
  56580. var newSound;
  56581. if (!sourceSound) {
  56582. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56583. scene._addPendingData(newSound);
  56584. }
  56585. else {
  56586. var setBufferAndRun = function () {
  56587. if (sourceSound._isReadyToPlay) {
  56588. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56589. newSound._isReadyToPlay = true;
  56590. if (newSound.autoplay) {
  56591. newSound.play();
  56592. }
  56593. }
  56594. else {
  56595. window.setTimeout(setBufferAndRun, 300);
  56596. }
  56597. };
  56598. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56599. setBufferAndRun();
  56600. }
  56601. if (parsedSound.position) {
  56602. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56603. newSound.setPosition(soundPosition);
  56604. }
  56605. if (parsedSound.isDirectional) {
  56606. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56607. if (parsedSound.localDirectionToMesh) {
  56608. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56609. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56610. }
  56611. }
  56612. if (parsedSound.connectedMeshId) {
  56613. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56614. if (connectedMesh) {
  56615. newSound.attachToMesh(connectedMesh);
  56616. }
  56617. }
  56618. return newSound;
  56619. };
  56620. return Sound;
  56621. }());
  56622. BABYLON.Sound = Sound;
  56623. })(BABYLON || (BABYLON = {}));
  56624. //# sourceMappingURL=babylon.sound.js.map
  56625. var BABYLON;
  56626. (function (BABYLON) {
  56627. var SoundTrack = /** @class */ (function () {
  56628. function SoundTrack(scene, options) {
  56629. this.id = -1;
  56630. this._isMainTrack = false;
  56631. this._isInitialized = false;
  56632. this._scene = scene;
  56633. this.soundCollection = new Array();
  56634. this._options = options;
  56635. if (!this._isMainTrack) {
  56636. this._scene.soundTracks.push(this);
  56637. this.id = this._scene.soundTracks.length - 1;
  56638. }
  56639. }
  56640. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56641. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56642. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56643. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56644. if (this._options) {
  56645. if (this._options.volume) {
  56646. this._outputAudioNode.gain.value = this._options.volume;
  56647. }
  56648. if (this._options.mainTrack) {
  56649. this._isMainTrack = this._options.mainTrack;
  56650. }
  56651. }
  56652. this._isInitialized = true;
  56653. }
  56654. };
  56655. SoundTrack.prototype.dispose = function () {
  56656. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56657. if (this._connectedAnalyser) {
  56658. this._connectedAnalyser.stopDebugCanvas();
  56659. }
  56660. while (this.soundCollection.length) {
  56661. this.soundCollection[0].dispose();
  56662. }
  56663. if (this._outputAudioNode) {
  56664. this._outputAudioNode.disconnect();
  56665. }
  56666. this._outputAudioNode = null;
  56667. }
  56668. };
  56669. SoundTrack.prototype.AddSound = function (sound) {
  56670. if (!this._isInitialized) {
  56671. this._initializeSoundTrackAudioGraph();
  56672. }
  56673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56674. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56675. }
  56676. if (sound.soundTrackId) {
  56677. if (sound.soundTrackId === -1) {
  56678. this._scene.mainSoundTrack.RemoveSound(sound);
  56679. }
  56680. else {
  56681. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56682. }
  56683. }
  56684. this.soundCollection.push(sound);
  56685. sound.soundTrackId = this.id;
  56686. };
  56687. SoundTrack.prototype.RemoveSound = function (sound) {
  56688. var index = this.soundCollection.indexOf(sound);
  56689. if (index !== -1) {
  56690. this.soundCollection.splice(index, 1);
  56691. }
  56692. };
  56693. SoundTrack.prototype.setVolume = function (newVolume) {
  56694. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56695. this._outputAudioNode.gain.value = newVolume;
  56696. }
  56697. };
  56698. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56699. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56700. for (var i = 0; i < this.soundCollection.length; i++) {
  56701. this.soundCollection[i].switchPanningModelToHRTF();
  56702. }
  56703. }
  56704. };
  56705. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56706. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56707. for (var i = 0; i < this.soundCollection.length; i++) {
  56708. this.soundCollection[i].switchPanningModelToEqualPower();
  56709. }
  56710. }
  56711. };
  56712. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56713. if (this._connectedAnalyser) {
  56714. this._connectedAnalyser.stopDebugCanvas();
  56715. }
  56716. this._connectedAnalyser = analyser;
  56717. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56718. this._outputAudioNode.disconnect();
  56719. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56720. }
  56721. };
  56722. return SoundTrack;
  56723. }());
  56724. BABYLON.SoundTrack = SoundTrack;
  56725. })(BABYLON || (BABYLON = {}));
  56726. //# sourceMappingURL=babylon.soundtrack.js.map
  56727. var BABYLON;
  56728. (function (BABYLON) {
  56729. var Analyser = /** @class */ (function () {
  56730. function Analyser(scene) {
  56731. this.SMOOTHING = 0.75;
  56732. this.FFT_SIZE = 512;
  56733. this.BARGRAPHAMPLITUDE = 256;
  56734. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56735. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56736. this._scene = scene;
  56737. this._audioEngine = BABYLON.Engine.audioEngine;
  56738. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56739. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56740. this._webAudioAnalyser.minDecibels = -140;
  56741. this._webAudioAnalyser.maxDecibels = 0;
  56742. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56743. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56744. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56745. }
  56746. }
  56747. Analyser.prototype.getFrequencyBinCount = function () {
  56748. if (this._audioEngine.canUseWebAudio) {
  56749. return this._webAudioAnalyser.frequencyBinCount;
  56750. }
  56751. else {
  56752. return 0;
  56753. }
  56754. };
  56755. Analyser.prototype.getByteFrequencyData = function () {
  56756. if (this._audioEngine.canUseWebAudio) {
  56757. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56758. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56759. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56760. }
  56761. return this._byteFreqs;
  56762. };
  56763. Analyser.prototype.getByteTimeDomainData = function () {
  56764. if (this._audioEngine.canUseWebAudio) {
  56765. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56766. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56767. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56768. }
  56769. return this._byteTime;
  56770. };
  56771. Analyser.prototype.getFloatFrequencyData = function () {
  56772. if (this._audioEngine.canUseWebAudio) {
  56773. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56774. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56775. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56776. }
  56777. return this._floatFreqs;
  56778. };
  56779. Analyser.prototype.drawDebugCanvas = function () {
  56780. var _this = this;
  56781. if (this._audioEngine.canUseWebAudio) {
  56782. if (!this._debugCanvas) {
  56783. this._debugCanvas = document.createElement("canvas");
  56784. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56785. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56786. this._debugCanvas.style.position = "absolute";
  56787. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56788. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56789. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56790. document.body.appendChild(this._debugCanvas);
  56791. this._registerFunc = function () {
  56792. _this.drawDebugCanvas();
  56793. };
  56794. this._scene.registerBeforeRender(this._registerFunc);
  56795. }
  56796. if (this._registerFunc && this._debugCanvasContext) {
  56797. var workingArray = this.getByteFrequencyData();
  56798. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56799. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56800. // Draw the frequency domain chart.
  56801. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56802. var value = workingArray[i];
  56803. var percent = value / this.BARGRAPHAMPLITUDE;
  56804. var height = this.DEBUGCANVASSIZE.height * percent;
  56805. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56806. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56807. var hue = i / this.getFrequencyBinCount() * 360;
  56808. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56809. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56810. }
  56811. }
  56812. }
  56813. };
  56814. Analyser.prototype.stopDebugCanvas = function () {
  56815. if (this._debugCanvas) {
  56816. if (this._registerFunc) {
  56817. this._scene.unregisterBeforeRender(this._registerFunc);
  56818. this._registerFunc = null;
  56819. }
  56820. document.body.removeChild(this._debugCanvas);
  56821. this._debugCanvas = null;
  56822. this._debugCanvasContext = null;
  56823. }
  56824. };
  56825. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56826. if (this._audioEngine.canUseWebAudio) {
  56827. inputAudioNode.connect(this._webAudioAnalyser);
  56828. this._webAudioAnalyser.connect(outputAudioNode);
  56829. }
  56830. };
  56831. Analyser.prototype.dispose = function () {
  56832. if (this._audioEngine.canUseWebAudio) {
  56833. this._webAudioAnalyser.disconnect();
  56834. }
  56835. };
  56836. return Analyser;
  56837. }());
  56838. BABYLON.Analyser = Analyser;
  56839. })(BABYLON || (BABYLON = {}));
  56840. //# sourceMappingURL=babylon.analyser.js.map
  56841. var BABYLON;
  56842. (function (BABYLON) {
  56843. var CubeTexture = /** @class */ (function (_super) {
  56844. __extends(CubeTexture, _super);
  56845. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56846. if (extensions === void 0) { extensions = null; }
  56847. if (noMipmap === void 0) { noMipmap = false; }
  56848. if (files === void 0) { files = null; }
  56849. if (onLoad === void 0) { onLoad = null; }
  56850. if (onError === void 0) { onError = null; }
  56851. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56852. if (prefiltered === void 0) { prefiltered = false; }
  56853. if (forcedExtension === void 0) { forcedExtension = null; }
  56854. var _this = _super.call(this, scene) || this;
  56855. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56856. /**
  56857. * Gets or sets the center of the bounding box associated with the cube texture
  56858. * It must define where the camera used to render the texture was set
  56859. */
  56860. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56861. _this.name = rootUrl;
  56862. _this.url = rootUrl;
  56863. _this._noMipmap = noMipmap;
  56864. _this.hasAlpha = false;
  56865. _this._format = format;
  56866. _this._prefiltered = prefiltered;
  56867. _this.isCube = true;
  56868. _this._textureMatrix = BABYLON.Matrix.Identity();
  56869. if (prefiltered) {
  56870. _this.gammaSpace = false;
  56871. }
  56872. if (!rootUrl && !files) {
  56873. return _this;
  56874. }
  56875. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56876. var lastDot = rootUrl.lastIndexOf(".");
  56877. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56878. var isDDS = (extension === ".dds");
  56879. if (!files) {
  56880. if (!isDDS && !extensions) {
  56881. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56882. }
  56883. files = [];
  56884. if (extensions) {
  56885. for (var index = 0; index < extensions.length; index++) {
  56886. files.push(rootUrl + extensions[index]);
  56887. }
  56888. }
  56889. }
  56890. _this._files = files;
  56891. if (!_this._texture) {
  56892. if (!scene.useDelayedTextureLoading) {
  56893. if (prefiltered) {
  56894. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56895. }
  56896. else {
  56897. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56898. }
  56899. }
  56900. else {
  56901. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56902. }
  56903. }
  56904. else if (onLoad) {
  56905. if (_this._texture.isReady) {
  56906. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56907. }
  56908. else {
  56909. _this._texture.onLoadedObservable.add(onLoad);
  56910. }
  56911. }
  56912. return _this;
  56913. }
  56914. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56915. get: function () {
  56916. return this._boundingBoxSize;
  56917. },
  56918. /**
  56919. * Gets or sets the size of the bounding box associated with the cube texture
  56920. * When defined, the cubemap will switch to local mode
  56921. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56922. * @example https://www.babylonjs-playground.com/#RNASML
  56923. */
  56924. set: function (value) {
  56925. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56926. return;
  56927. }
  56928. this._boundingBoxSize = value;
  56929. var scene = this.getScene();
  56930. if (scene) {
  56931. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56932. }
  56933. },
  56934. enumerable: true,
  56935. configurable: true
  56936. });
  56937. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56938. var rootUrlKey = "";
  56939. files.forEach(function (url) { return rootUrlKey += url; });
  56940. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  56941. };
  56942. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56943. if (forcedExtension === void 0) { forcedExtension = null; }
  56944. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56945. };
  56946. // Methods
  56947. CubeTexture.prototype.delayLoad = function () {
  56948. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56949. return;
  56950. }
  56951. var scene = this.getScene();
  56952. if (!scene) {
  56953. return;
  56954. }
  56955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56956. this._texture = this._getFromCache(this.url, this._noMipmap);
  56957. if (!this._texture) {
  56958. if (this._prefiltered) {
  56959. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56960. }
  56961. else {
  56962. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56963. }
  56964. }
  56965. };
  56966. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56967. return this._textureMatrix;
  56968. };
  56969. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56970. this._textureMatrix = value;
  56971. };
  56972. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56973. var texture = BABYLON.SerializationHelper.Parse(function () {
  56974. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56975. }, parsedTexture, scene);
  56976. // Local Cubemaps
  56977. if (parsedTexture.boundingBoxPosition) {
  56978. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  56979. }
  56980. if (parsedTexture.boundingBoxSize) {
  56981. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  56982. }
  56983. // Animations
  56984. if (parsedTexture.animations) {
  56985. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56986. var parsedAnimation = parsedTexture.animations[animationIndex];
  56987. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56988. }
  56989. }
  56990. return texture;
  56991. };
  56992. CubeTexture.prototype.clone = function () {
  56993. var _this = this;
  56994. return BABYLON.SerializationHelper.Clone(function () {
  56995. var scene = _this.getScene();
  56996. if (!scene) {
  56997. return _this;
  56998. }
  56999. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57000. }, this);
  57001. };
  57002. return CubeTexture;
  57003. }(BABYLON.BaseTexture));
  57004. BABYLON.CubeTexture = CubeTexture;
  57005. })(BABYLON || (BABYLON = {}));
  57006. //# sourceMappingURL=babylon.cubeTexture.js.map
  57007. var BABYLON;
  57008. (function (BABYLON) {
  57009. var RenderTargetTexture = /** @class */ (function (_super) {
  57010. __extends(RenderTargetTexture, _super);
  57011. /**
  57012. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57013. * or used a shadow, depth texture...
  57014. * @param name The friendly name of the texture
  57015. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  57016. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57017. * @param generateMipMaps True if mip maps need to be generated after render.
  57018. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57019. * @param type The type of the buffer in the RTT (int, half float, float...)
  57020. * @param isCube True if a cube texture needs to be created
  57021. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57022. * @param generateDepthBuffer True to generate a depth buffer
  57023. * @param generateStencilBuffer True to generate a stencil buffer
  57024. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57025. */
  57026. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57027. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57028. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57029. if (isCube === void 0) { isCube = false; }
  57030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57031. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57032. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57033. if (isMulti === void 0) { isMulti = false; }
  57034. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57035. _this.isCube = isCube;
  57036. /**
  57037. * Use this list to define the list of mesh you want to render.
  57038. */
  57039. _this.renderList = new Array();
  57040. _this.renderParticles = true;
  57041. _this.renderSprites = false;
  57042. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57043. _this.ignoreCameraViewport = false;
  57044. // Events
  57045. /**
  57046. * An event triggered when the texture is unbind.
  57047. * @type {BABYLON.Observable}
  57048. */
  57049. _this.onBeforeBindObservable = new BABYLON.Observable();
  57050. /**
  57051. * An event triggered when the texture is unbind.
  57052. * @type {BABYLON.Observable}
  57053. */
  57054. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57055. /**
  57056. * An event triggered before rendering the texture
  57057. * @type {BABYLON.Observable}
  57058. */
  57059. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57060. /**
  57061. * An event triggered after rendering the texture
  57062. * @type {BABYLON.Observable}
  57063. */
  57064. _this.onAfterRenderObservable = new BABYLON.Observable();
  57065. /**
  57066. * An event triggered after the texture clear
  57067. * @type {BABYLON.Observable}
  57068. */
  57069. _this.onClearObservable = new BABYLON.Observable();
  57070. _this._currentRefreshId = -1;
  57071. _this._refreshRate = 1;
  57072. _this._samples = 1;
  57073. /**
  57074. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57075. * It must define where the camera used to render the texture is set
  57076. */
  57077. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57078. scene = _this.getScene();
  57079. if (!scene) {
  57080. return _this;
  57081. }
  57082. _this._engine = scene.getEngine();
  57083. _this.name = name;
  57084. _this.isRenderTarget = true;
  57085. _this._initialSizeParameter = size;
  57086. _this._processSizeParameter(size);
  57087. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57088. });
  57089. _this._generateMipMaps = generateMipMaps ? true : false;
  57090. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57091. // Rendering groups
  57092. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57093. if (isMulti) {
  57094. return _this;
  57095. }
  57096. _this._renderTargetOptions = {
  57097. generateMipMaps: generateMipMaps,
  57098. type: type,
  57099. samplingMode: samplingMode,
  57100. generateDepthBuffer: generateDepthBuffer,
  57101. generateStencilBuffer: generateStencilBuffer
  57102. };
  57103. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57104. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57105. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57106. }
  57107. if (isCube) {
  57108. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57109. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57110. _this._textureMatrix = BABYLON.Matrix.Identity();
  57111. }
  57112. else {
  57113. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57114. }
  57115. return _this;
  57116. }
  57117. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57118. get: function () {
  57119. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57120. },
  57121. enumerable: true,
  57122. configurable: true
  57123. });
  57124. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57125. get: function () {
  57126. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57127. },
  57128. enumerable: true,
  57129. configurable: true
  57130. });
  57131. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57132. get: function () {
  57133. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57134. },
  57135. enumerable: true,
  57136. configurable: true
  57137. });
  57138. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57139. set: function (callback) {
  57140. if (this._onAfterUnbindObserver) {
  57141. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57142. }
  57143. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57144. },
  57145. enumerable: true,
  57146. configurable: true
  57147. });
  57148. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57149. set: function (callback) {
  57150. if (this._onBeforeRenderObserver) {
  57151. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57152. }
  57153. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57154. },
  57155. enumerable: true,
  57156. configurable: true
  57157. });
  57158. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57159. set: function (callback) {
  57160. if (this._onAfterRenderObserver) {
  57161. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57162. }
  57163. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57164. },
  57165. enumerable: true,
  57166. configurable: true
  57167. });
  57168. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57169. set: function (callback) {
  57170. if (this._onClearObserver) {
  57171. this.onClearObservable.remove(this._onClearObserver);
  57172. }
  57173. this._onClearObserver = this.onClearObservable.add(callback);
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57179. get: function () {
  57180. return this._renderTargetOptions;
  57181. },
  57182. enumerable: true,
  57183. configurable: true
  57184. });
  57185. RenderTargetTexture.prototype._onRatioRescale = function () {
  57186. if (this._sizeRatio) {
  57187. this.resize(this._initialSizeParameter);
  57188. }
  57189. };
  57190. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57191. get: function () {
  57192. return this._boundingBoxSize;
  57193. },
  57194. /**
  57195. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57196. * When defined, the cubemap will switch to local mode
  57197. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57198. * @example https://www.babylonjs-playground.com/#RNASML
  57199. */
  57200. set: function (value) {
  57201. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57202. return;
  57203. }
  57204. this._boundingBoxSize = value;
  57205. var scene = this.getScene();
  57206. if (scene) {
  57207. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57208. }
  57209. },
  57210. enumerable: true,
  57211. configurable: true
  57212. });
  57213. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57214. if (size.ratio) {
  57215. this._sizeRatio = size.ratio;
  57216. this._size = {
  57217. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57218. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57219. };
  57220. }
  57221. else {
  57222. this._size = size;
  57223. }
  57224. };
  57225. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57226. get: function () {
  57227. return this._samples;
  57228. },
  57229. set: function (value) {
  57230. if (this._samples === value) {
  57231. return;
  57232. }
  57233. var scene = this.getScene();
  57234. if (!scene) {
  57235. return;
  57236. }
  57237. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57238. },
  57239. enumerable: true,
  57240. configurable: true
  57241. });
  57242. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57243. this._currentRefreshId = -1;
  57244. };
  57245. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57246. get: function () {
  57247. return this._refreshRate;
  57248. },
  57249. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57250. set: function (value) {
  57251. this._refreshRate = value;
  57252. this.resetRefreshCounter();
  57253. },
  57254. enumerable: true,
  57255. configurable: true
  57256. });
  57257. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57258. if (!this._postProcessManager) {
  57259. var scene = this.getScene();
  57260. if (!scene) {
  57261. return;
  57262. }
  57263. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57264. this._postProcesses = new Array();
  57265. }
  57266. this._postProcesses.push(postProcess);
  57267. this._postProcesses[0].autoClear = false;
  57268. };
  57269. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57270. if (!this._postProcesses) {
  57271. return;
  57272. }
  57273. if (dispose) {
  57274. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57275. var postProcess = _a[_i];
  57276. postProcess.dispose();
  57277. }
  57278. }
  57279. this._postProcesses = [];
  57280. };
  57281. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57282. if (!this._postProcesses) {
  57283. return;
  57284. }
  57285. var index = this._postProcesses.indexOf(postProcess);
  57286. if (index === -1) {
  57287. return;
  57288. }
  57289. this._postProcesses.splice(index, 1);
  57290. if (this._postProcesses.length > 0) {
  57291. this._postProcesses[0].autoClear = false;
  57292. }
  57293. };
  57294. RenderTargetTexture.prototype._shouldRender = function () {
  57295. if (this._currentRefreshId === -1) {
  57296. this._currentRefreshId = 1;
  57297. return true;
  57298. }
  57299. if (this.refreshRate === this._currentRefreshId) {
  57300. this._currentRefreshId = 1;
  57301. return true;
  57302. }
  57303. this._currentRefreshId++;
  57304. return false;
  57305. };
  57306. RenderTargetTexture.prototype.getRenderSize = function () {
  57307. if (this._size.width) {
  57308. return this._size.width;
  57309. }
  57310. return this._size;
  57311. };
  57312. RenderTargetTexture.prototype.getRenderWidth = function () {
  57313. if (this._size.width) {
  57314. return this._size.width;
  57315. }
  57316. return this._size;
  57317. };
  57318. RenderTargetTexture.prototype.getRenderHeight = function () {
  57319. if (this._size.width) {
  57320. return this._size.height;
  57321. }
  57322. return this._size;
  57323. };
  57324. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57325. get: function () {
  57326. return true;
  57327. },
  57328. enumerable: true,
  57329. configurable: true
  57330. });
  57331. RenderTargetTexture.prototype.scale = function (ratio) {
  57332. var newSize = this.getRenderSize() * ratio;
  57333. this.resize(newSize);
  57334. };
  57335. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57336. if (this.isCube) {
  57337. return this._textureMatrix;
  57338. }
  57339. return _super.prototype.getReflectionTextureMatrix.call(this);
  57340. };
  57341. RenderTargetTexture.prototype.resize = function (size) {
  57342. this.releaseInternalTexture();
  57343. var scene = this.getScene();
  57344. if (!scene) {
  57345. return;
  57346. }
  57347. this._processSizeParameter(size);
  57348. if (this.isCube) {
  57349. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57350. }
  57351. else {
  57352. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57353. }
  57354. };
  57355. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57356. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57357. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57358. var scene = this.getScene();
  57359. if (!scene) {
  57360. return;
  57361. }
  57362. var engine = scene.getEngine();
  57363. if (this.useCameraPostProcesses !== undefined) {
  57364. useCameraPostProcess = this.useCameraPostProcesses;
  57365. }
  57366. if (this._waitingRenderList) {
  57367. this.renderList = [];
  57368. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57369. var id = this._waitingRenderList[index];
  57370. var mesh_1 = scene.getMeshByID(id);
  57371. if (mesh_1) {
  57372. this.renderList.push(mesh_1);
  57373. }
  57374. }
  57375. delete this._waitingRenderList;
  57376. }
  57377. // Is predicate defined?
  57378. if (this.renderListPredicate) {
  57379. if (this.renderList) {
  57380. this.renderList.splice(0); // Clear previous renderList
  57381. }
  57382. else {
  57383. this.renderList = [];
  57384. }
  57385. var scene = this.getScene();
  57386. if (!scene) {
  57387. return;
  57388. }
  57389. var sceneMeshes = scene.meshes;
  57390. for (var index = 0; index < sceneMeshes.length; index++) {
  57391. var mesh = sceneMeshes[index];
  57392. if (this.renderListPredicate(mesh)) {
  57393. this.renderList.push(mesh);
  57394. }
  57395. }
  57396. }
  57397. this.onBeforeBindObservable.notifyObservers(this);
  57398. // Set custom projection.
  57399. // Needs to be before binding to prevent changing the aspect ratio.
  57400. var camera;
  57401. if (this.activeCamera) {
  57402. camera = this.activeCamera;
  57403. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57404. if (this.activeCamera !== scene.activeCamera) {
  57405. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57406. }
  57407. }
  57408. else {
  57409. camera = scene.activeCamera;
  57410. if (camera) {
  57411. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57412. }
  57413. }
  57414. // Prepare renderingManager
  57415. this._renderingManager.reset();
  57416. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57417. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57418. var sceneRenderId = scene.getRenderId();
  57419. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57420. var mesh = currentRenderList[meshIndex];
  57421. if (mesh) {
  57422. if (!mesh.isReady()) {
  57423. // Reset _currentRefreshId
  57424. this.resetRefreshCounter();
  57425. continue;
  57426. }
  57427. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57428. var isMasked = void 0;
  57429. if (!this.renderList && camera) {
  57430. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57431. }
  57432. else {
  57433. isMasked = false;
  57434. }
  57435. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57436. mesh._activate(sceneRenderId);
  57437. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57438. var subMesh = mesh.subMeshes[subIndex];
  57439. scene._activeIndices.addCount(subMesh.indexCount, false);
  57440. this._renderingManager.dispatch(subMesh, mesh);
  57441. }
  57442. }
  57443. }
  57444. }
  57445. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57446. var particleSystem = scene.particleSystems[particleIndex];
  57447. var emitter = particleSystem.emitter;
  57448. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57449. continue;
  57450. }
  57451. if (currentRenderList.indexOf(emitter) >= 0) {
  57452. this._renderingManager.dispatchParticles(particleSystem);
  57453. }
  57454. }
  57455. if (this.isCube) {
  57456. for (var face = 0; face < 6; face++) {
  57457. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57458. scene.incrementRenderId();
  57459. scene.resetCachedMaterial();
  57460. }
  57461. }
  57462. else {
  57463. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57464. }
  57465. this.onAfterUnbindObservable.notifyObservers(this);
  57466. if (scene.activeCamera) {
  57467. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57468. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57469. }
  57470. engine.setViewport(scene.activeCamera.viewport);
  57471. }
  57472. scene.resetCachedMaterial();
  57473. };
  57474. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57475. var minimum = 128;
  57476. var x = renderDimension * scale;
  57477. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57478. // Ensure we don't exceed the render dimension (while staying POT)
  57479. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57480. };
  57481. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57482. var _this = this;
  57483. if (!this._texture) {
  57484. return;
  57485. }
  57486. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57487. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57488. });
  57489. };
  57490. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57491. var scene = this.getScene();
  57492. if (!scene) {
  57493. return;
  57494. }
  57495. var engine = scene.getEngine();
  57496. if (!this._texture) {
  57497. return;
  57498. }
  57499. // Bind
  57500. if (this._postProcessManager) {
  57501. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57502. }
  57503. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57504. if (this._texture) {
  57505. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57506. }
  57507. }
  57508. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57509. // Clear
  57510. if (this.onClearObservable.hasObservers()) {
  57511. this.onClearObservable.notifyObservers(engine);
  57512. }
  57513. else {
  57514. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57515. }
  57516. if (!this._doNotChangeAspectRatio) {
  57517. scene.updateTransformMatrix(true);
  57518. }
  57519. // Render
  57520. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57521. if (this._postProcessManager) {
  57522. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57523. }
  57524. else if (useCameraPostProcess) {
  57525. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57526. }
  57527. if (!this._doNotChangeAspectRatio) {
  57528. scene.updateTransformMatrix(true);
  57529. }
  57530. // Dump ?
  57531. if (dumpForDebug) {
  57532. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57533. }
  57534. // Unbind
  57535. if (!this.isCube || faceIndex === 5) {
  57536. if (this.isCube) {
  57537. if (faceIndex === 5) {
  57538. engine.generateMipMapsForCubemap(this._texture);
  57539. }
  57540. }
  57541. this.unbindFrameBuffer(engine, faceIndex);
  57542. }
  57543. else {
  57544. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57545. }
  57546. };
  57547. /**
  57548. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57549. * This allowed control for front to back rendering or reversly depending of the special needs.
  57550. *
  57551. * @param renderingGroupId The rendering group id corresponding to its index
  57552. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57553. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57554. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57555. */
  57556. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57557. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57558. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57559. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57560. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57561. };
  57562. /**
  57563. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57564. *
  57565. * @param renderingGroupId The rendering group id corresponding to its index
  57566. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57567. */
  57568. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57569. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57570. };
  57571. RenderTargetTexture.prototype.clone = function () {
  57572. var textureSize = this.getSize();
  57573. 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);
  57574. // Base texture
  57575. newTexture.hasAlpha = this.hasAlpha;
  57576. newTexture.level = this.level;
  57577. // RenderTarget Texture
  57578. newTexture.coordinatesMode = this.coordinatesMode;
  57579. if (this.renderList) {
  57580. newTexture.renderList = this.renderList.slice(0);
  57581. }
  57582. return newTexture;
  57583. };
  57584. RenderTargetTexture.prototype.serialize = function () {
  57585. if (!this.name) {
  57586. return null;
  57587. }
  57588. var serializationObject = _super.prototype.serialize.call(this);
  57589. serializationObject.renderTargetSize = this.getRenderSize();
  57590. serializationObject.renderList = [];
  57591. if (this.renderList) {
  57592. for (var index = 0; index < this.renderList.length; index++) {
  57593. serializationObject.renderList.push(this.renderList[index].id);
  57594. }
  57595. }
  57596. return serializationObject;
  57597. };
  57598. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57599. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57600. var objBuffer = this.getInternalTexture();
  57601. var scene = this.getScene();
  57602. if (objBuffer && scene) {
  57603. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57604. }
  57605. };
  57606. RenderTargetTexture.prototype.dispose = function () {
  57607. if (this._postProcessManager) {
  57608. this._postProcessManager.dispose();
  57609. this._postProcessManager = null;
  57610. }
  57611. this.clearPostProcesses(true);
  57612. if (this._resizeObserver) {
  57613. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57614. this._resizeObserver = null;
  57615. }
  57616. this.renderList = null;
  57617. // Remove from custom render targets
  57618. var scene = this.getScene();
  57619. if (!scene) {
  57620. return;
  57621. }
  57622. var index = scene.customRenderTargets.indexOf(this);
  57623. if (index >= 0) {
  57624. scene.customRenderTargets.splice(index, 1);
  57625. }
  57626. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57627. var camera = _a[_i];
  57628. index = camera.customRenderTargets.indexOf(this);
  57629. if (index >= 0) {
  57630. camera.customRenderTargets.splice(index, 1);
  57631. }
  57632. }
  57633. _super.prototype.dispose.call(this);
  57634. };
  57635. RenderTargetTexture.prototype._rebuild = function () {
  57636. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57637. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57638. }
  57639. if (this._postProcessManager) {
  57640. this._postProcessManager._rebuild();
  57641. }
  57642. };
  57643. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57644. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57645. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57646. return RenderTargetTexture;
  57647. }(BABYLON.Texture));
  57648. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57649. })(BABYLON || (BABYLON = {}));
  57650. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57651. var BABYLON;
  57652. (function (BABYLON) {
  57653. ;
  57654. var MultiRenderTarget = /** @class */ (function (_super) {
  57655. __extends(MultiRenderTarget, _super);
  57656. function MultiRenderTarget(name, size, count, scene, options) {
  57657. var _this = this;
  57658. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57659. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57660. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57661. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57662. _this._engine = scene.getEngine();
  57663. if (!_this.isSupported) {
  57664. _this.dispose();
  57665. return;
  57666. }
  57667. var types = [];
  57668. var samplingModes = [];
  57669. for (var i = 0; i < count; i++) {
  57670. if (options && options.types && options.types[i] !== undefined) {
  57671. types.push(options.types[i]);
  57672. }
  57673. else {
  57674. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57675. }
  57676. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57677. samplingModes.push(options.samplingModes[i]);
  57678. }
  57679. else {
  57680. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57681. }
  57682. }
  57683. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57684. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57685. _this._size = size;
  57686. _this._multiRenderTargetOptions = {
  57687. samplingModes: samplingModes,
  57688. generateMipMaps: generateMipMaps,
  57689. generateDepthBuffer: generateDepthBuffer,
  57690. generateStencilBuffer: generateStencilBuffer,
  57691. generateDepthTexture: generateDepthTexture,
  57692. types: types,
  57693. textureCount: count
  57694. };
  57695. _this._createInternalTextures();
  57696. _this._createTextures();
  57697. return _this;
  57698. }
  57699. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57700. get: function () {
  57701. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57702. },
  57703. enumerable: true,
  57704. configurable: true
  57705. });
  57706. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57707. get: function () {
  57708. return this._textures;
  57709. },
  57710. enumerable: true,
  57711. configurable: true
  57712. });
  57713. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57714. get: function () {
  57715. return this._textures[this._textures.length - 1];
  57716. },
  57717. enumerable: true,
  57718. configurable: true
  57719. });
  57720. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57721. set: function (wrap) {
  57722. if (this._textures) {
  57723. for (var i = 0; i < this._textures.length; i++) {
  57724. this._textures[i].wrapU = wrap;
  57725. }
  57726. }
  57727. },
  57728. enumerable: true,
  57729. configurable: true
  57730. });
  57731. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57732. set: function (wrap) {
  57733. if (this._textures) {
  57734. for (var i = 0; i < this._textures.length; i++) {
  57735. this._textures[i].wrapV = wrap;
  57736. }
  57737. }
  57738. },
  57739. enumerable: true,
  57740. configurable: true
  57741. });
  57742. MultiRenderTarget.prototype._rebuild = function () {
  57743. this.releaseInternalTextures();
  57744. this._createInternalTextures();
  57745. for (var i = 0; i < this._internalTextures.length; i++) {
  57746. var texture = this._textures[i];
  57747. texture._texture = this._internalTextures[i];
  57748. }
  57749. // Keeps references to frame buffer and stencil/depth buffer
  57750. this._texture = this._internalTextures[0];
  57751. };
  57752. MultiRenderTarget.prototype._createInternalTextures = function () {
  57753. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57754. };
  57755. MultiRenderTarget.prototype._createTextures = function () {
  57756. this._textures = [];
  57757. for (var i = 0; i < this._internalTextures.length; i++) {
  57758. var texture = new BABYLON.Texture(null, this.getScene());
  57759. texture._texture = this._internalTextures[i];
  57760. this._textures.push(texture);
  57761. }
  57762. // Keeps references to frame buffer and stencil/depth buffer
  57763. this._texture = this._internalTextures[0];
  57764. };
  57765. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57766. get: function () {
  57767. return this._samples;
  57768. },
  57769. set: function (value) {
  57770. if (this._samples === value) {
  57771. return;
  57772. }
  57773. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57774. },
  57775. enumerable: true,
  57776. configurable: true
  57777. });
  57778. MultiRenderTarget.prototype.resize = function (size) {
  57779. this.releaseInternalTextures();
  57780. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57781. this._createInternalTextures();
  57782. };
  57783. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57784. var _this = this;
  57785. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57786. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57787. });
  57788. };
  57789. MultiRenderTarget.prototype.dispose = function () {
  57790. this.releaseInternalTextures();
  57791. _super.prototype.dispose.call(this);
  57792. };
  57793. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57794. if (!this._internalTextures) {
  57795. return;
  57796. }
  57797. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57798. if (this._internalTextures[i] !== undefined) {
  57799. this._internalTextures[i].dispose();
  57800. this._internalTextures.splice(i, 1);
  57801. }
  57802. }
  57803. };
  57804. return MultiRenderTarget;
  57805. }(BABYLON.RenderTargetTexture));
  57806. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57807. })(BABYLON || (BABYLON = {}));
  57808. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57809. var BABYLON;
  57810. (function (BABYLON) {
  57811. var MirrorTexture = /** @class */ (function (_super) {
  57812. __extends(MirrorTexture, _super);
  57813. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57814. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57816. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57817. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57818. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57819. _this._transformMatrix = BABYLON.Matrix.Zero();
  57820. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57821. _this._adaptiveBlurKernel = 0;
  57822. _this._blurKernelX = 0;
  57823. _this._blurKernelY = 0;
  57824. _this._blurRatio = 1.0;
  57825. _this.ignoreCameraViewport = true;
  57826. _this.onBeforeRenderObservable.add(function () {
  57827. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57828. _this._savedViewMatrix = scene.getViewMatrix();
  57829. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57830. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57831. scene.clipPlane = _this.mirrorPlane;
  57832. scene.getEngine().cullBackFaces = false;
  57833. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57834. });
  57835. _this.onAfterRenderObservable.add(function () {
  57836. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57837. scene.getEngine().cullBackFaces = true;
  57838. scene._mirroredCameraPosition = null;
  57839. delete scene.clipPlane;
  57840. });
  57841. return _this;
  57842. }
  57843. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57844. get: function () {
  57845. return this._blurRatio;
  57846. },
  57847. set: function (value) {
  57848. if (this._blurRatio === value) {
  57849. return;
  57850. }
  57851. this._blurRatio = value;
  57852. this._preparePostProcesses();
  57853. },
  57854. enumerable: true,
  57855. configurable: true
  57856. });
  57857. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57858. set: function (value) {
  57859. this._adaptiveBlurKernel = value;
  57860. this._autoComputeBlurKernel();
  57861. },
  57862. enumerable: true,
  57863. configurable: true
  57864. });
  57865. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57866. set: function (value) {
  57867. this.blurKernelX = value;
  57868. this.blurKernelY = value;
  57869. },
  57870. enumerable: true,
  57871. configurable: true
  57872. });
  57873. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57874. get: function () {
  57875. return this._blurKernelX;
  57876. },
  57877. set: function (value) {
  57878. if (this._blurKernelX === value) {
  57879. return;
  57880. }
  57881. this._blurKernelX = value;
  57882. this._preparePostProcesses();
  57883. },
  57884. enumerable: true,
  57885. configurable: true
  57886. });
  57887. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57888. get: function () {
  57889. return this._blurKernelY;
  57890. },
  57891. set: function (value) {
  57892. if (this._blurKernelY === value) {
  57893. return;
  57894. }
  57895. this._blurKernelY = value;
  57896. this._preparePostProcesses();
  57897. },
  57898. enumerable: true,
  57899. configurable: true
  57900. });
  57901. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57902. var engine = this.getScene().getEngine();
  57903. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57904. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57905. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57906. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57907. };
  57908. MirrorTexture.prototype._onRatioRescale = function () {
  57909. if (this._sizeRatio) {
  57910. this.resize(this._initialSizeParameter);
  57911. if (!this._adaptiveBlurKernel) {
  57912. this._preparePostProcesses();
  57913. }
  57914. }
  57915. if (this._adaptiveBlurKernel) {
  57916. this._autoComputeBlurKernel();
  57917. }
  57918. };
  57919. MirrorTexture.prototype._preparePostProcesses = function () {
  57920. this.clearPostProcesses(true);
  57921. if (this._blurKernelX && this._blurKernelY) {
  57922. var engine = this.getScene().getEngine();
  57923. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57924. 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);
  57925. this._blurX.autoClear = false;
  57926. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57927. this._blurX.inputTexture = this._texture;
  57928. }
  57929. else {
  57930. this._blurX.alwaysForcePOT = true;
  57931. }
  57932. 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);
  57933. this._blurY.autoClear = false;
  57934. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57935. this.addPostProcess(this._blurX);
  57936. this.addPostProcess(this._blurY);
  57937. }
  57938. else {
  57939. if (this._blurY) {
  57940. this.removePostProcess(this._blurY);
  57941. this._blurY.dispose();
  57942. this._blurY = null;
  57943. }
  57944. if (this._blurX) {
  57945. this.removePostProcess(this._blurX);
  57946. this._blurX.dispose();
  57947. this._blurX = null;
  57948. }
  57949. }
  57950. };
  57951. MirrorTexture.prototype.clone = function () {
  57952. var scene = this.getScene();
  57953. if (!scene) {
  57954. return this;
  57955. }
  57956. var textureSize = this.getSize();
  57957. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57958. // Base texture
  57959. newTexture.hasAlpha = this.hasAlpha;
  57960. newTexture.level = this.level;
  57961. // Mirror Texture
  57962. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57963. if (this.renderList) {
  57964. newTexture.renderList = this.renderList.slice(0);
  57965. }
  57966. return newTexture;
  57967. };
  57968. MirrorTexture.prototype.serialize = function () {
  57969. if (!this.name) {
  57970. return null;
  57971. }
  57972. var serializationObject = _super.prototype.serialize.call(this);
  57973. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57974. return serializationObject;
  57975. };
  57976. return MirrorTexture;
  57977. }(BABYLON.RenderTargetTexture));
  57978. BABYLON.MirrorTexture = MirrorTexture;
  57979. })(BABYLON || (BABYLON = {}));
  57980. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57981. var BABYLON;
  57982. (function (BABYLON) {
  57983. /**
  57984. * Creates a refraction texture used by refraction channel of the standard material.
  57985. * @param name the texture name
  57986. * @param size size of the underlying texture
  57987. * @param scene root scene
  57988. */
  57989. var RefractionTexture = /** @class */ (function (_super) {
  57990. __extends(RefractionTexture, _super);
  57991. function RefractionTexture(name, size, scene, generateMipMaps) {
  57992. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57993. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57994. _this.depth = 2.0;
  57995. _this.onBeforeRenderObservable.add(function () {
  57996. scene.clipPlane = _this.refractionPlane;
  57997. });
  57998. _this.onAfterRenderObservable.add(function () {
  57999. delete scene.clipPlane;
  58000. });
  58001. return _this;
  58002. }
  58003. RefractionTexture.prototype.clone = function () {
  58004. var scene = this.getScene();
  58005. if (!scene) {
  58006. return this;
  58007. }
  58008. var textureSize = this.getSize();
  58009. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58010. // Base texture
  58011. newTexture.hasAlpha = this.hasAlpha;
  58012. newTexture.level = this.level;
  58013. // Refraction Texture
  58014. newTexture.refractionPlane = this.refractionPlane.clone();
  58015. if (this.renderList) {
  58016. newTexture.renderList = this.renderList.slice(0);
  58017. }
  58018. newTexture.depth = this.depth;
  58019. return newTexture;
  58020. };
  58021. RefractionTexture.prototype.serialize = function () {
  58022. if (!this.name) {
  58023. return null;
  58024. }
  58025. var serializationObject = _super.prototype.serialize.call(this);
  58026. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58027. serializationObject.depth = this.depth;
  58028. return serializationObject;
  58029. };
  58030. return RefractionTexture;
  58031. }(BABYLON.RenderTargetTexture));
  58032. BABYLON.RefractionTexture = RefractionTexture;
  58033. })(BABYLON || (BABYLON = {}));
  58034. //# sourceMappingURL=babylon.refractionTexture.js.map
  58035. var BABYLON;
  58036. (function (BABYLON) {
  58037. var DynamicTexture = /** @class */ (function (_super) {
  58038. __extends(DynamicTexture, _super);
  58039. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58040. if (scene === void 0) { scene = null; }
  58041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58042. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58043. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58044. _this.name = name;
  58045. _this._engine = _this.getScene().getEngine();
  58046. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58047. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58048. _this._generateMipMaps = generateMipMaps;
  58049. if (options.getContext) {
  58050. _this._canvas = options;
  58051. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58052. }
  58053. else {
  58054. _this._canvas = document.createElement("canvas");
  58055. if (options.width) {
  58056. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58057. }
  58058. else {
  58059. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58060. }
  58061. }
  58062. var textureSize = _this.getSize();
  58063. _this._canvas.width = textureSize.width;
  58064. _this._canvas.height = textureSize.height;
  58065. _this._context = _this._canvas.getContext("2d");
  58066. return _this;
  58067. }
  58068. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58069. get: function () {
  58070. return true;
  58071. },
  58072. enumerable: true,
  58073. configurable: true
  58074. });
  58075. DynamicTexture.prototype._recreate = function (textureSize) {
  58076. this._canvas.width = textureSize.width;
  58077. this._canvas.height = textureSize.height;
  58078. this.releaseInternalTexture();
  58079. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58080. };
  58081. DynamicTexture.prototype.scale = function (ratio) {
  58082. var textureSize = this.getSize();
  58083. textureSize.width *= ratio;
  58084. textureSize.height *= ratio;
  58085. this._recreate(textureSize);
  58086. };
  58087. DynamicTexture.prototype.scaleTo = function (width, height) {
  58088. var textureSize = this.getSize();
  58089. textureSize.width = width;
  58090. textureSize.height = height;
  58091. this._recreate(textureSize);
  58092. };
  58093. DynamicTexture.prototype.getContext = function () {
  58094. return this._context;
  58095. };
  58096. DynamicTexture.prototype.clear = function () {
  58097. var size = this.getSize();
  58098. this._context.fillRect(0, 0, size.width, size.height);
  58099. };
  58100. DynamicTexture.prototype.update = function (invertY) {
  58101. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58102. };
  58103. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58104. if (update === void 0) { update = true; }
  58105. var size = this.getSize();
  58106. if (clearColor) {
  58107. this._context.fillStyle = clearColor;
  58108. this._context.fillRect(0, 0, size.width, size.height);
  58109. }
  58110. this._context.font = font;
  58111. if (x === null || x === undefined) {
  58112. var textSize = this._context.measureText(text);
  58113. x = (size.width - textSize.width) / 2;
  58114. }
  58115. if (y === null || y === undefined) {
  58116. var fontSize = parseInt((font.replace(/\D/g, '')));
  58117. ;
  58118. y = (size.height / 2) + (fontSize / 3.65);
  58119. }
  58120. this._context.fillStyle = color;
  58121. this._context.fillText(text, x, y);
  58122. if (update) {
  58123. this.update(invertY);
  58124. }
  58125. };
  58126. DynamicTexture.prototype.clone = function () {
  58127. var scene = this.getScene();
  58128. if (!scene) {
  58129. return this;
  58130. }
  58131. var textureSize = this.getSize();
  58132. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58133. // Base texture
  58134. newTexture.hasAlpha = this.hasAlpha;
  58135. newTexture.level = this.level;
  58136. // Dynamic Texture
  58137. newTexture.wrapU = this.wrapU;
  58138. newTexture.wrapV = this.wrapV;
  58139. return newTexture;
  58140. };
  58141. DynamicTexture.prototype._rebuild = function () {
  58142. this.update();
  58143. };
  58144. return DynamicTexture;
  58145. }(BABYLON.Texture));
  58146. BABYLON.DynamicTexture = DynamicTexture;
  58147. })(BABYLON || (BABYLON = {}));
  58148. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58149. var BABYLON;
  58150. (function (BABYLON) {
  58151. var VideoTexture = /** @class */ (function (_super) {
  58152. __extends(VideoTexture, _super);
  58153. /**
  58154. * Creates a video texture.
  58155. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58156. * @param {string | null} name optional name, will detect from video source, if not defined
  58157. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58158. * @param {BABYLON.Scene} scene is obviously the current scene.
  58159. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58160. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58161. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58162. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58163. */
  58164. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58165. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58166. if (invertY === void 0) { invertY = false; }
  58167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58168. if (settings === void 0) { settings = {
  58169. autoPlay: true,
  58170. loop: true,
  58171. autoUpdateTexture: true,
  58172. }; }
  58173. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58174. _this._createInternalTexture = function () {
  58175. if (_this._texture != null) {
  58176. return;
  58177. }
  58178. if (!_this._engine.needPOTTextures ||
  58179. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58180. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58181. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58182. }
  58183. else {
  58184. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58185. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58186. _this._generateMipMaps = false;
  58187. }
  58188. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58189. _this._texture.isReady = true;
  58190. _this._updateInternalTexture();
  58191. };
  58192. _this.reset = function () {
  58193. if (_this._texture == null) {
  58194. return;
  58195. }
  58196. _this._texture.dispose();
  58197. _this._texture = null;
  58198. };
  58199. _this._updateInternalTexture = function (e) {
  58200. if (_this._texture == null || !_this._texture.isReady) {
  58201. return;
  58202. }
  58203. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58204. return;
  58205. }
  58206. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58207. };
  58208. _this._engine = _this.getScene().getEngine();
  58209. _this._generateMipMaps = generateMipMaps;
  58210. _this._samplingMode = samplingMode;
  58211. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58212. _this.name = name || _this._getName(src);
  58213. _this.video = _this._getVideo(src);
  58214. if (settings.autoPlay !== undefined) {
  58215. _this.video.autoplay = settings.autoPlay;
  58216. }
  58217. if (settings.loop !== undefined) {
  58218. _this.video.loop = settings.loop;
  58219. }
  58220. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58221. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58222. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58223. _this.video.addEventListener("emptied", _this.reset);
  58224. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58225. _this._createInternalTexture();
  58226. }
  58227. return _this;
  58228. }
  58229. VideoTexture.prototype._getName = function (src) {
  58230. if (src instanceof HTMLVideoElement) {
  58231. return src.currentSrc;
  58232. }
  58233. if (typeof src === "object") {
  58234. return src.toString();
  58235. }
  58236. return src;
  58237. };
  58238. ;
  58239. VideoTexture.prototype._getVideo = function (src) {
  58240. if (src instanceof HTMLVideoElement) {
  58241. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58242. return src;
  58243. }
  58244. var video = document.createElement("video");
  58245. if (typeof src === "string") {
  58246. BABYLON.Tools.SetCorsBehavior(src, video);
  58247. video.src = src;
  58248. }
  58249. else {
  58250. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58251. src.forEach(function (url) {
  58252. var source = document.createElement("source");
  58253. source.src = url;
  58254. video.appendChild(source);
  58255. });
  58256. }
  58257. return video;
  58258. };
  58259. ;
  58260. /**
  58261. * Internal method to initiate `update`.
  58262. */
  58263. VideoTexture.prototype._rebuild = function () {
  58264. this.update();
  58265. };
  58266. /**
  58267. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58268. */
  58269. VideoTexture.prototype.update = function () {
  58270. if (!this.autoUpdateTexture) {
  58271. // Expecting user to call `updateTexture` manually
  58272. return;
  58273. }
  58274. this.updateTexture(true);
  58275. };
  58276. /**
  58277. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58278. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58279. */
  58280. VideoTexture.prototype.updateTexture = function (isVisible) {
  58281. if (!isVisible) {
  58282. return;
  58283. }
  58284. if (this.video.paused) {
  58285. return;
  58286. }
  58287. this._updateInternalTexture();
  58288. };
  58289. /**
  58290. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58291. * @param url New url.
  58292. */
  58293. VideoTexture.prototype.updateURL = function (url) {
  58294. this.video.src = url;
  58295. };
  58296. VideoTexture.prototype.dispose = function () {
  58297. _super.prototype.dispose.call(this);
  58298. this.video.removeEventListener("canplay", this._createInternalTexture);
  58299. this.video.removeEventListener("paused", this._updateInternalTexture);
  58300. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58301. this.video.removeEventListener("emptied", this.reset);
  58302. };
  58303. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58304. var video = document.createElement("video");
  58305. var constraintsDeviceId;
  58306. if (constraints && constraints.deviceId) {
  58307. constraintsDeviceId = {
  58308. exact: constraints.deviceId,
  58309. };
  58310. }
  58311. navigator.getUserMedia =
  58312. navigator.getUserMedia ||
  58313. navigator.webkitGetUserMedia ||
  58314. navigator.mozGetUserMedia ||
  58315. navigator.msGetUserMedia;
  58316. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58317. if (navigator.getUserMedia) {
  58318. navigator.getUserMedia({
  58319. video: {
  58320. deviceId: constraintsDeviceId,
  58321. width: {
  58322. min: (constraints && constraints.minWidth) || 256,
  58323. max: (constraints && constraints.maxWidth) || 640,
  58324. },
  58325. height: {
  58326. min: (constraints && constraints.minHeight) || 256,
  58327. max: (constraints && constraints.maxHeight) || 480,
  58328. },
  58329. },
  58330. }, function (stream) {
  58331. if (video.mozSrcObject !== undefined) {
  58332. // hack for Firefox < 19
  58333. video.mozSrcObject = stream;
  58334. }
  58335. else {
  58336. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58337. }
  58338. video.play();
  58339. if (onReady) {
  58340. onReady(new VideoTexture("video", video, scene, true, true));
  58341. }
  58342. }, function (e) {
  58343. BABYLON.Tools.Error(e.name);
  58344. });
  58345. }
  58346. };
  58347. return VideoTexture;
  58348. }(BABYLON.Texture));
  58349. BABYLON.VideoTexture = VideoTexture;
  58350. })(BABYLON || (BABYLON = {}));
  58351. //# sourceMappingURL=babylon.videoTexture.js.map
  58352. var BABYLON;
  58353. (function (BABYLON) {
  58354. var RawTexture = /** @class */ (function (_super) {
  58355. __extends(RawTexture, _super);
  58356. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58357. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58358. if (invertY === void 0) { invertY = false; }
  58359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58360. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58361. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58362. _this.format = format;
  58363. _this._engine = scene.getEngine();
  58364. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58365. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58366. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58367. return _this;
  58368. }
  58369. RawTexture.prototype.update = function (data) {
  58370. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58371. };
  58372. // Statics
  58373. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58374. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58375. if (invertY === void 0) { invertY = false; }
  58376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58377. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58378. };
  58379. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58380. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58381. if (invertY === void 0) { invertY = false; }
  58382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58384. };
  58385. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58387. if (invertY === void 0) { invertY = false; }
  58388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58389. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58390. };
  58391. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58393. if (invertY === void 0) { invertY = false; }
  58394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58395. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58396. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58397. };
  58398. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58399. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58400. if (invertY === void 0) { invertY = false; }
  58401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58402. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58403. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58404. };
  58405. return RawTexture;
  58406. }(BABYLON.Texture));
  58407. BABYLON.RawTexture = RawTexture;
  58408. })(BABYLON || (BABYLON = {}));
  58409. //# sourceMappingURL=babylon.rawTexture.js.map
  58410. var BABYLON;
  58411. (function (BABYLON) {
  58412. /**
  58413. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58414. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58415. */
  58416. var PostProcess = /** @class */ (function () {
  58417. /**
  58418. * Creates a new instance of @see PostProcess
  58419. * @param name The name of the PostProcess.
  58420. * @param fragmentUrl The url of the fragment shader to be used.
  58421. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58422. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58423. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58424. * @param camera The camera to apply the render pass to.
  58425. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58426. * @param engine The engine which the post process will be applied. (default: current engine)
  58427. * @param reusable If the post process can be reused on the same frame. (default: false)
  58428. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58429. * @param textureType Type of textures used when performing the post process. (default: 0)
  58430. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58431. * @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
  58432. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58433. */
  58434. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58436. if (defines === void 0) { defines = null; }
  58437. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58438. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58439. if (blockCompilation === void 0) { blockCompilation = false; }
  58440. this.name = name;
  58441. /**
  58442. * Width of the texture to apply the post process on
  58443. */
  58444. this.width = -1;
  58445. /**
  58446. * Height of the texture to apply the post process on
  58447. */
  58448. this.height = -1;
  58449. /**
  58450. * If the buffer needs to be cleared before applying the post process. (default: true)
  58451. * Should be set to false if shader will overwrite all previous pixels.
  58452. */
  58453. this.autoClear = true;
  58454. /**
  58455. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58456. */
  58457. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58458. /**
  58459. * Animations to be used for the post processing
  58460. */
  58461. this.animations = new Array();
  58462. /**
  58463. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58464. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58465. */
  58466. this.enablePixelPerfectMode = false;
  58467. /**
  58468. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58469. */
  58470. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58471. /**
  58472. * Force textures to be a power of two (default: false)
  58473. */
  58474. this.alwaysForcePOT = false;
  58475. /**
  58476. * Number of sample textures (default: 1)
  58477. */
  58478. this.samples = 1;
  58479. /**
  58480. * Modify the scale of the post process to be the same as the viewport (default: false)
  58481. */
  58482. this.adaptScaleToCurrentViewport = false;
  58483. this._reusable = false;
  58484. /**
  58485. * Smart array of input and output textures for the post process.
  58486. */
  58487. this._textures = new BABYLON.SmartArray(2);
  58488. /**
  58489. * The index in _textures that corresponds to the output texture.
  58490. */
  58491. this._currentRenderTextureInd = 0;
  58492. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58493. this._texelSize = BABYLON.Vector2.Zero();
  58494. // Events
  58495. /**
  58496. * An event triggered when the postprocess is activated.
  58497. * @type {BABYLON.Observable}
  58498. */
  58499. this.onActivateObservable = new BABYLON.Observable();
  58500. /**
  58501. * An event triggered when the postprocess changes its size.
  58502. * @type {BABYLON.Observable}
  58503. */
  58504. this.onSizeChangedObservable = new BABYLON.Observable();
  58505. /**
  58506. * An event triggered when the postprocess applies its effect.
  58507. * @type {BABYLON.Observable}
  58508. */
  58509. this.onApplyObservable = new BABYLON.Observable();
  58510. /**
  58511. * An event triggered before rendering the postprocess
  58512. * @type {BABYLON.Observable}
  58513. */
  58514. this.onBeforeRenderObservable = new BABYLON.Observable();
  58515. /**
  58516. * An event triggered after rendering the postprocess
  58517. * @type {BABYLON.Observable}
  58518. */
  58519. this.onAfterRenderObservable = new BABYLON.Observable();
  58520. if (camera != null) {
  58521. this._camera = camera;
  58522. this._scene = camera.getScene();
  58523. camera.attachPostProcess(this);
  58524. this._engine = this._scene.getEngine();
  58525. this._scene.postProcesses.push(this);
  58526. }
  58527. else if (engine) {
  58528. this._engine = engine;
  58529. this._engine.postProcesses.push(this);
  58530. }
  58531. this._options = options;
  58532. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58533. this._reusable = reusable || false;
  58534. this._textureType = textureType;
  58535. this._samplers = samplers || [];
  58536. this._samplers.push("textureSampler");
  58537. this._fragmentUrl = fragmentUrl;
  58538. this._vertexUrl = vertexUrl;
  58539. this._parameters = parameters || [];
  58540. this._parameters.push("scale");
  58541. this._indexParameters = indexParameters;
  58542. if (!blockCompilation) {
  58543. this.updateEffect(defines);
  58544. }
  58545. }
  58546. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58547. /**
  58548. * A function that is added to the onActivateObservable
  58549. */
  58550. set: function (callback) {
  58551. if (this._onActivateObserver) {
  58552. this.onActivateObservable.remove(this._onActivateObserver);
  58553. }
  58554. if (callback) {
  58555. this._onActivateObserver = this.onActivateObservable.add(callback);
  58556. }
  58557. },
  58558. enumerable: true,
  58559. configurable: true
  58560. });
  58561. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58562. /**
  58563. * A function that is added to the onSizeChangedObservable
  58564. */
  58565. set: function (callback) {
  58566. if (this._onSizeChangedObserver) {
  58567. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58568. }
  58569. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58570. },
  58571. enumerable: true,
  58572. configurable: true
  58573. });
  58574. Object.defineProperty(PostProcess.prototype, "onApply", {
  58575. /**
  58576. * A function that is added to the onApplyObservable
  58577. */
  58578. set: function (callback) {
  58579. if (this._onApplyObserver) {
  58580. this.onApplyObservable.remove(this._onApplyObserver);
  58581. }
  58582. this._onApplyObserver = this.onApplyObservable.add(callback);
  58583. },
  58584. enumerable: true,
  58585. configurable: true
  58586. });
  58587. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58588. /**
  58589. * A function that is added to the onBeforeRenderObservable
  58590. */
  58591. set: function (callback) {
  58592. if (this._onBeforeRenderObserver) {
  58593. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58594. }
  58595. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58596. },
  58597. enumerable: true,
  58598. configurable: true
  58599. });
  58600. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58601. /**
  58602. * A function that is added to the onAfterRenderObservable
  58603. */
  58604. set: function (callback) {
  58605. if (this._onAfterRenderObserver) {
  58606. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58607. }
  58608. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58609. },
  58610. enumerable: true,
  58611. configurable: true
  58612. });
  58613. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58614. /**
  58615. * 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
  58616. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58617. */
  58618. get: function () {
  58619. return this._textures.data[this._currentRenderTextureInd];
  58620. },
  58621. set: function (value) {
  58622. this._forcedOutputTexture = value;
  58623. },
  58624. enumerable: true,
  58625. configurable: true
  58626. });
  58627. /**
  58628. * Gets the camera which post process is applied to.
  58629. * @returns The camera the post process is applied to.
  58630. */
  58631. PostProcess.prototype.getCamera = function () {
  58632. return this._camera;
  58633. };
  58634. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58635. /**
  58636. * Gets the texel size of the postprocess.
  58637. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58638. */
  58639. get: function () {
  58640. if (this._shareOutputWithPostProcess) {
  58641. return this._shareOutputWithPostProcess.texelSize;
  58642. }
  58643. if (this._forcedOutputTexture) {
  58644. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58645. }
  58646. return this._texelSize;
  58647. },
  58648. enumerable: true,
  58649. configurable: true
  58650. });
  58651. /**
  58652. * Gets the engine which this post process belongs to.
  58653. * @returns The engine the post process was enabled with.
  58654. */
  58655. PostProcess.prototype.getEngine = function () {
  58656. return this._engine;
  58657. };
  58658. /**
  58659. * The effect that is created when initializing the post process.
  58660. * @returns The created effect corrisponding the the postprocess.
  58661. */
  58662. PostProcess.prototype.getEffect = function () {
  58663. return this._effect;
  58664. };
  58665. /**
  58666. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58667. * @param postProcess The post process to share the output with.
  58668. * @returns This post process.
  58669. */
  58670. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58671. this._disposeTextures();
  58672. this._shareOutputWithPostProcess = postProcess;
  58673. return this;
  58674. };
  58675. /**
  58676. * Updates the effect with the current post process compile time values and recompiles the shader.
  58677. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58678. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58679. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58680. * @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
  58681. * @param onCompiled Called when the shader has been compiled.
  58682. * @param onError Called if there is an error when compiling a shader.
  58683. */
  58684. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58685. if (defines === void 0) { defines = null; }
  58686. if (uniforms === void 0) { uniforms = null; }
  58687. if (samplers === void 0) { samplers = null; }
  58688. 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);
  58689. };
  58690. /**
  58691. * The post process is reusable if it can be used multiple times within one frame.
  58692. * @returns If the post process is reusable
  58693. */
  58694. PostProcess.prototype.isReusable = function () {
  58695. return this._reusable;
  58696. };
  58697. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58698. PostProcess.prototype.markTextureDirty = function () {
  58699. this.width = -1;
  58700. };
  58701. /**
  58702. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58703. * 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.
  58704. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58705. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58706. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58707. */
  58708. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58709. var _this = this;
  58710. if (sourceTexture === void 0) { sourceTexture = null; }
  58711. camera = camera || this._camera;
  58712. var scene = camera.getScene();
  58713. var engine = scene.getEngine();
  58714. var maxSize = engine.getCaps().maxTextureSize;
  58715. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58716. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58717. var desiredWidth = (this._options.width || requiredWidth);
  58718. var desiredHeight = this._options.height || requiredHeight;
  58719. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58720. if (this.adaptScaleToCurrentViewport) {
  58721. var currentViewport = engine.currentViewport;
  58722. if (currentViewport) {
  58723. desiredWidth *= currentViewport.width;
  58724. desiredHeight *= currentViewport.height;
  58725. }
  58726. }
  58727. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58728. if (!this._options.width) {
  58729. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58730. }
  58731. if (!this._options.height) {
  58732. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58733. }
  58734. }
  58735. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58736. if (this._textures.length > 0) {
  58737. for (var i = 0; i < this._textures.length; i++) {
  58738. this._engine._releaseTexture(this._textures.data[i]);
  58739. }
  58740. this._textures.reset();
  58741. }
  58742. this.width = desiredWidth;
  58743. this.height = desiredHeight;
  58744. var textureSize = { width: this.width, height: this.height };
  58745. var textureOptions = {
  58746. generateMipMaps: false,
  58747. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58748. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58749. samplingMode: this.renderTargetSamplingMode,
  58750. type: this._textureType
  58751. };
  58752. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58753. if (this._reusable) {
  58754. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58755. }
  58756. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58757. this.onSizeChangedObservable.notifyObservers(this);
  58758. }
  58759. this._textures.forEach(function (texture) {
  58760. if (texture.samples !== _this.samples) {
  58761. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58762. }
  58763. });
  58764. }
  58765. var target;
  58766. if (this._shareOutputWithPostProcess) {
  58767. target = this._shareOutputWithPostProcess.inputTexture;
  58768. }
  58769. else if (this._forcedOutputTexture) {
  58770. target = this._forcedOutputTexture;
  58771. this.width = this._forcedOutputTexture.width;
  58772. this.height = this._forcedOutputTexture.height;
  58773. }
  58774. else {
  58775. target = this.inputTexture;
  58776. }
  58777. // Bind the input of this post process to be used as the output of the previous post process.
  58778. if (this.enablePixelPerfectMode) {
  58779. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58780. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58781. }
  58782. else {
  58783. this._scaleRatio.copyFromFloats(1, 1);
  58784. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58785. }
  58786. this.onActivateObservable.notifyObservers(camera);
  58787. // Clear
  58788. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58789. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58790. }
  58791. if (this._reusable) {
  58792. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58793. }
  58794. };
  58795. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58796. /**
  58797. * If the post process is supported.
  58798. */
  58799. get: function () {
  58800. return this._effect.isSupported;
  58801. },
  58802. enumerable: true,
  58803. configurable: true
  58804. });
  58805. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58806. /**
  58807. * The aspect ratio of the output texture.
  58808. */
  58809. get: function () {
  58810. if (this._shareOutputWithPostProcess) {
  58811. return this._shareOutputWithPostProcess.aspectRatio;
  58812. }
  58813. if (this._forcedOutputTexture) {
  58814. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58815. }
  58816. return this.width / this.height;
  58817. },
  58818. enumerable: true,
  58819. configurable: true
  58820. });
  58821. /**
  58822. * Get a value indicating if the post-process is ready to be used
  58823. * @returns true if the post-process is ready (shader is compiled)
  58824. */
  58825. PostProcess.prototype.isReady = function () {
  58826. return this._effect && this._effect.isReady();
  58827. };
  58828. /**
  58829. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58830. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58831. */
  58832. PostProcess.prototype.apply = function () {
  58833. // Check
  58834. if (!this._effect || !this._effect.isReady())
  58835. return null;
  58836. // States
  58837. this._engine.enableEffect(this._effect);
  58838. this._engine.setState(false);
  58839. this._engine.setDepthBuffer(false);
  58840. this._engine.setDepthWrite(false);
  58841. // Alpha
  58842. this._engine.setAlphaMode(this.alphaMode);
  58843. if (this.alphaConstants) {
  58844. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58845. }
  58846. // Bind the output texture of the preivous post process as the input to this post process.
  58847. var source;
  58848. if (this._shareOutputWithPostProcess) {
  58849. source = this._shareOutputWithPostProcess.inputTexture;
  58850. }
  58851. else if (this._forcedOutputTexture) {
  58852. source = this._forcedOutputTexture;
  58853. }
  58854. else {
  58855. source = this.inputTexture;
  58856. }
  58857. this._effect._bindTexture("textureSampler", source);
  58858. // Parameters
  58859. this._effect.setVector2("scale", this._scaleRatio);
  58860. this.onApplyObservable.notifyObservers(this._effect);
  58861. return this._effect;
  58862. };
  58863. PostProcess.prototype._disposeTextures = function () {
  58864. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58865. return;
  58866. }
  58867. if (this._textures.length > 0) {
  58868. for (var i = 0; i < this._textures.length; i++) {
  58869. this._engine._releaseTexture(this._textures.data[i]);
  58870. }
  58871. }
  58872. this._textures.dispose();
  58873. };
  58874. /**
  58875. * Disposes the post process.
  58876. * @param camera The camera to dispose the post process on.
  58877. */
  58878. PostProcess.prototype.dispose = function (camera) {
  58879. camera = camera || this._camera;
  58880. this._disposeTextures();
  58881. if (this._scene) {
  58882. var index_1 = this._scene.postProcesses.indexOf(this);
  58883. if (index_1 !== -1) {
  58884. this._scene.postProcesses.splice(index_1, 1);
  58885. }
  58886. }
  58887. else {
  58888. var index_2 = this._engine.postProcesses.indexOf(this);
  58889. if (index_2 !== -1) {
  58890. this._engine.postProcesses.splice(index_2, 1);
  58891. }
  58892. }
  58893. if (!camera) {
  58894. return;
  58895. }
  58896. camera.detachPostProcess(this);
  58897. var index = camera._postProcesses.indexOf(this);
  58898. if (index === 0 && camera._postProcesses.length > 0) {
  58899. this._camera._postProcesses[0].markTextureDirty();
  58900. }
  58901. this.onActivateObservable.clear();
  58902. this.onAfterRenderObservable.clear();
  58903. this.onApplyObservable.clear();
  58904. this.onBeforeRenderObservable.clear();
  58905. this.onSizeChangedObservable.clear();
  58906. };
  58907. return PostProcess;
  58908. }());
  58909. BABYLON.PostProcess = PostProcess;
  58910. })(BABYLON || (BABYLON = {}));
  58911. //# sourceMappingURL=babylon.postProcess.js.map
  58912. var BABYLON;
  58913. (function (BABYLON) {
  58914. var PassPostProcess = /** @class */ (function (_super) {
  58915. __extends(PassPostProcess, _super);
  58916. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58917. if (camera === void 0) { camera = null; }
  58918. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58919. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58920. }
  58921. return PassPostProcess;
  58922. }(BABYLON.PostProcess));
  58923. BABYLON.PassPostProcess = PassPostProcess;
  58924. })(BABYLON || (BABYLON = {}));
  58925. //# sourceMappingURL=babylon.passPostProcess.js.map
  58926. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58927. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58928. s = arguments[i];
  58929. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58930. t[p] = s[p];
  58931. }
  58932. return t;
  58933. };
  58934. var BABYLON;
  58935. (function (BABYLON) {
  58936. /**
  58937. * Default implementation of @see IShadowGenerator.
  58938. * This is the main object responsible of generating shadows in the framework.
  58939. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58940. */
  58941. var ShadowGenerator = /** @class */ (function () {
  58942. /**
  58943. * Creates a ShadowGenerator object.
  58944. * A ShadowGenerator is the required tool to use the shadows.
  58945. * Each light casting shadows needs to use its own ShadowGenerator.
  58946. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58947. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58948. * @param light The light object generating the shadows.
  58949. * @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.
  58950. */
  58951. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58952. this._bias = 0.00005;
  58953. this._blurBoxOffset = 1;
  58954. this._blurScale = 2;
  58955. this._blurKernel = 1;
  58956. this._useKernelBlur = false;
  58957. this._filter = ShadowGenerator.FILTER_NONE;
  58958. this._darkness = 0;
  58959. this._transparencyShadow = false;
  58960. /**
  58961. * Controls the extent to which the shadows fade out at the edge of the frustum
  58962. * Used only by directionals and spots
  58963. */
  58964. this.frustumEdgeFalloff = 0;
  58965. /**
  58966. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58967. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58968. * It might on the other hand introduce peter panning.
  58969. */
  58970. this.forceBackFacesOnly = false;
  58971. this._lightDirection = BABYLON.Vector3.Zero();
  58972. this._viewMatrix = BABYLON.Matrix.Zero();
  58973. this._projectionMatrix = BABYLON.Matrix.Zero();
  58974. this._transformMatrix = BABYLON.Matrix.Zero();
  58975. this._currentFaceIndex = 0;
  58976. this._currentFaceIndexCache = 0;
  58977. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58978. this._mapSize = mapSize;
  58979. this._light = light;
  58980. this._scene = light.getScene();
  58981. light._shadowGenerator = this;
  58982. // Texture type fallback from float to int if not supported.
  58983. var caps = this._scene.getEngine().getCaps();
  58984. if (!useFullFloatFirst) {
  58985. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58986. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58987. }
  58988. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58989. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58990. }
  58991. else {
  58992. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58993. }
  58994. }
  58995. else {
  58996. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58997. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58998. }
  58999. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59000. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59001. }
  59002. else {
  59003. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59004. }
  59005. }
  59006. this._initializeGenerator();
  59007. }
  59008. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59009. /**
  59010. * Shadow generator mode None: no filtering applied.
  59011. */
  59012. get: function () {
  59013. return ShadowGenerator._FILTER_NONE;
  59014. },
  59015. enumerable: true,
  59016. configurable: true
  59017. });
  59018. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59019. /**
  59020. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59021. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59022. */
  59023. get: function () {
  59024. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59025. },
  59026. enumerable: true,
  59027. configurable: true
  59028. });
  59029. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59030. /**
  59031. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59032. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59033. */
  59034. get: function () {
  59035. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59041. /**
  59042. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59043. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59044. */
  59045. get: function () {
  59046. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59047. },
  59048. enumerable: true,
  59049. configurable: true
  59050. });
  59051. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59052. /**
  59053. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59054. * edge artifacts on steep falloff.
  59055. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59056. */
  59057. get: function () {
  59058. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59059. },
  59060. enumerable: true,
  59061. configurable: true
  59062. });
  59063. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59064. /**
  59065. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59066. * edge artifacts on steep falloff.
  59067. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59068. */
  59069. get: function () {
  59070. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59071. },
  59072. enumerable: true,
  59073. configurable: true
  59074. });
  59075. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59076. /**
  59077. * Gets the bias: offset applied on the depth preventing acnea.
  59078. */
  59079. get: function () {
  59080. return this._bias;
  59081. },
  59082. /**
  59083. * Sets the bias: offset applied on the depth preventing acnea.
  59084. */
  59085. set: function (bias) {
  59086. this._bias = bias;
  59087. },
  59088. enumerable: true,
  59089. configurable: true
  59090. });
  59091. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59092. /**
  59093. * Gets the blur box offset: offset applied during the blur pass.
  59094. * Only usefull if useKernelBlur = false
  59095. */
  59096. get: function () {
  59097. return this._blurBoxOffset;
  59098. },
  59099. /**
  59100. * Sets the blur box offset: offset applied during the blur pass.
  59101. * Only usefull if useKernelBlur = false
  59102. */
  59103. set: function (value) {
  59104. if (this._blurBoxOffset === value) {
  59105. return;
  59106. }
  59107. this._blurBoxOffset = value;
  59108. this._disposeBlurPostProcesses();
  59109. },
  59110. enumerable: true,
  59111. configurable: true
  59112. });
  59113. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59114. /**
  59115. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59116. * 2 means half of the size.
  59117. */
  59118. get: function () {
  59119. return this._blurScale;
  59120. },
  59121. /**
  59122. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59123. * 2 means half of the size.
  59124. */
  59125. set: function (value) {
  59126. if (this._blurScale === value) {
  59127. return;
  59128. }
  59129. this._blurScale = value;
  59130. this._disposeBlurPostProcesses();
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59136. /**
  59137. * Gets the blur kernel: kernel size of the blur pass.
  59138. * Only usefull if useKernelBlur = true
  59139. */
  59140. get: function () {
  59141. return this._blurKernel;
  59142. },
  59143. /**
  59144. * Sets the blur kernel: kernel size of the blur pass.
  59145. * Only usefull if useKernelBlur = true
  59146. */
  59147. set: function (value) {
  59148. if (this._blurKernel === value) {
  59149. return;
  59150. }
  59151. this._blurKernel = value;
  59152. this._disposeBlurPostProcesses();
  59153. },
  59154. enumerable: true,
  59155. configurable: true
  59156. });
  59157. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59158. /**
  59159. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59160. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59161. */
  59162. get: function () {
  59163. return this._useKernelBlur;
  59164. },
  59165. /**
  59166. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59167. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59168. */
  59169. set: function (value) {
  59170. if (this._useKernelBlur === value) {
  59171. return;
  59172. }
  59173. this._useKernelBlur = value;
  59174. this._disposeBlurPostProcesses();
  59175. },
  59176. enumerable: true,
  59177. configurable: true
  59178. });
  59179. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59180. /**
  59181. * Gets the depth scale used in ESM mode.
  59182. */
  59183. get: function () {
  59184. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59185. },
  59186. /**
  59187. * Sets the depth scale used in ESM mode.
  59188. * This can override the scale stored on the light.
  59189. */
  59190. set: function (value) {
  59191. this._depthScale = value;
  59192. },
  59193. enumerable: true,
  59194. configurable: true
  59195. });
  59196. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59197. /**
  59198. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59199. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59200. */
  59201. get: function () {
  59202. return this._filter;
  59203. },
  59204. /**
  59205. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59206. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59207. */
  59208. set: function (value) {
  59209. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59210. if (this._light.needCube()) {
  59211. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59212. this.useExponentialShadowMap = true;
  59213. return;
  59214. }
  59215. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59216. this.useCloseExponentialShadowMap = true;
  59217. return;
  59218. }
  59219. }
  59220. if (this._filter === value) {
  59221. return;
  59222. }
  59223. this._filter = value;
  59224. this._disposeBlurPostProcesses();
  59225. this._applyFilterValues();
  59226. this._light._markMeshesAsLightDirty();
  59227. },
  59228. enumerable: true,
  59229. configurable: true
  59230. });
  59231. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59232. /**
  59233. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59234. */
  59235. get: function () {
  59236. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59237. },
  59238. /**
  59239. * Sets the current filter to Poisson Sampling aka PCF.
  59240. */
  59241. set: function (value) {
  59242. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59243. return;
  59244. }
  59245. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59246. },
  59247. enumerable: true,
  59248. configurable: true
  59249. });
  59250. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59251. /**
  59252. * Gets if the current filter is set to VSM.
  59253. * DEPRECATED. Should use useExponentialShadowMap instead.
  59254. */
  59255. get: function () {
  59256. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59257. return this.useExponentialShadowMap;
  59258. },
  59259. /**
  59260. * Sets the current filter is to VSM.
  59261. * DEPRECATED. Should use useExponentialShadowMap instead.
  59262. */
  59263. set: function (value) {
  59264. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59265. this.useExponentialShadowMap = value;
  59266. },
  59267. enumerable: true,
  59268. configurable: true
  59269. });
  59270. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59271. /**
  59272. * Gets if the current filter is set to blurred VSM.
  59273. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59274. */
  59275. get: function () {
  59276. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59277. return this.useBlurExponentialShadowMap;
  59278. },
  59279. /**
  59280. * Sets the current filter is to blurred VSM.
  59281. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59282. */
  59283. set: function (value) {
  59284. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59285. this.useBlurExponentialShadowMap = value;
  59286. },
  59287. enumerable: true,
  59288. configurable: true
  59289. });
  59290. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59291. /**
  59292. * Gets if the current filter is set to ESM.
  59293. */
  59294. get: function () {
  59295. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59296. },
  59297. /**
  59298. * Sets the current filter is to ESM.
  59299. */
  59300. set: function (value) {
  59301. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59302. return;
  59303. }
  59304. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59305. },
  59306. enumerable: true,
  59307. configurable: true
  59308. });
  59309. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59310. /**
  59311. * Gets if the current filter is set to filtered ESM.
  59312. */
  59313. get: function () {
  59314. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59315. },
  59316. /**
  59317. * Gets if the current filter is set to filtered ESM.
  59318. */
  59319. set: function (value) {
  59320. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59321. return;
  59322. }
  59323. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59324. },
  59325. enumerable: true,
  59326. configurable: true
  59327. });
  59328. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59329. /**
  59330. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59331. * exponential to prevent steep falloff artifacts).
  59332. */
  59333. get: function () {
  59334. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59335. },
  59336. /**
  59337. * Sets the current filter to "close ESM" (using the inverse of the
  59338. * exponential to prevent steep falloff artifacts).
  59339. */
  59340. set: function (value) {
  59341. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59342. return;
  59343. }
  59344. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59345. },
  59346. enumerable: true,
  59347. configurable: true
  59348. });
  59349. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59350. /**
  59351. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59352. * exponential to prevent steep falloff artifacts).
  59353. */
  59354. get: function () {
  59355. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59356. },
  59357. /**
  59358. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59359. * exponential to prevent steep falloff artifacts).
  59360. */
  59361. set: function (value) {
  59362. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59363. return;
  59364. }
  59365. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59366. },
  59367. enumerable: true,
  59368. configurable: true
  59369. });
  59370. /**
  59371. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59372. * 0 means strongest and 1 would means no shadow.
  59373. * @returns the darkness.
  59374. */
  59375. ShadowGenerator.prototype.getDarkness = function () {
  59376. return this._darkness;
  59377. };
  59378. /**
  59379. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59380. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59381. * @returns the shadow generator allowing fluent coding.
  59382. */
  59383. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59384. if (darkness >= 1.0)
  59385. this._darkness = 1.0;
  59386. else if (darkness <= 0.0)
  59387. this._darkness = 0.0;
  59388. else
  59389. this._darkness = darkness;
  59390. return this;
  59391. };
  59392. /**
  59393. * Sets the ability to have transparent shadow (boolean).
  59394. * @param transparent True if transparent else False
  59395. * @returns the shadow generator allowing fluent coding
  59396. */
  59397. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59398. this._transparencyShadow = transparent;
  59399. return this;
  59400. };
  59401. /**
  59402. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59403. * @returns The render target texture if present otherwise, null
  59404. */
  59405. ShadowGenerator.prototype.getShadowMap = function () {
  59406. return this._shadowMap;
  59407. };
  59408. /**
  59409. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59410. * @returns The render target texture if the shadow map is present otherwise, null
  59411. */
  59412. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59413. if (this._shadowMap2) {
  59414. return this._shadowMap2;
  59415. }
  59416. return this._shadowMap;
  59417. };
  59418. /**
  59419. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59420. * @param mesh Mesh to add
  59421. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59422. * @returns the Shadow Generator itself
  59423. */
  59424. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59425. if (includeDescendants === void 0) { includeDescendants = true; }
  59426. if (!this._shadowMap) {
  59427. return this;
  59428. }
  59429. if (!this._shadowMap.renderList) {
  59430. this._shadowMap.renderList = [];
  59431. }
  59432. this._shadowMap.renderList.push(mesh);
  59433. if (includeDescendants) {
  59434. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59435. }
  59436. return this;
  59437. var _a;
  59438. };
  59439. /**
  59440. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59441. * @param mesh Mesh to remove
  59442. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59443. * @returns the Shadow Generator itself
  59444. */
  59445. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59446. if (includeDescendants === void 0) { includeDescendants = true; }
  59447. if (!this._shadowMap || !this._shadowMap.renderList) {
  59448. return this;
  59449. }
  59450. var index = this._shadowMap.renderList.indexOf(mesh);
  59451. if (index !== -1) {
  59452. this._shadowMap.renderList.splice(index, 1);
  59453. }
  59454. if (includeDescendants) {
  59455. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59456. var child = _a[_i];
  59457. this.removeShadowCaster(child);
  59458. }
  59459. }
  59460. return this;
  59461. };
  59462. /**
  59463. * Returns the associated light object.
  59464. * @returns the light generating the shadow
  59465. */
  59466. ShadowGenerator.prototype.getLight = function () {
  59467. return this._light;
  59468. };
  59469. ShadowGenerator.prototype._initializeGenerator = function () {
  59470. this._light._markMeshesAsLightDirty();
  59471. this._initializeShadowMap();
  59472. };
  59473. ShadowGenerator.prototype._initializeShadowMap = function () {
  59474. var _this = this;
  59475. // Render target
  59476. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59477. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59478. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59479. this._shadowMap.anisotropicFilteringLevel = 1;
  59480. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59481. this._shadowMap.renderParticles = false;
  59482. this._shadowMap.ignoreCameraViewport = true;
  59483. // Record Face Index before render.
  59484. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59485. _this._currentFaceIndex = faceIndex;
  59486. });
  59487. // Custom render function.
  59488. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59489. // Blur if required afer render.
  59490. this._shadowMap.onAfterUnbindObservable.add(function () {
  59491. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59492. return;
  59493. }
  59494. var shadowMap = _this.getShadowMapForRendering();
  59495. if (shadowMap) {
  59496. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59497. }
  59498. });
  59499. // Clear according to the chosen filter.
  59500. this._shadowMap.onClearObservable.add(function (engine) {
  59501. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59502. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59503. }
  59504. else {
  59505. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59506. }
  59507. });
  59508. };
  59509. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59510. var _this = this;
  59511. var engine = this._scene.getEngine();
  59512. var targetSize = this._mapSize / this.blurScale;
  59513. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59514. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59515. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59516. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59517. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59518. }
  59519. if (this.useKernelBlur) {
  59520. 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);
  59521. this._kernelBlurXPostprocess.width = targetSize;
  59522. this._kernelBlurXPostprocess.height = targetSize;
  59523. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59524. effect.setTexture("textureSampler", _this._shadowMap);
  59525. });
  59526. 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);
  59527. this._kernelBlurXPostprocess.autoClear = false;
  59528. this._kernelBlurYPostprocess.autoClear = false;
  59529. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59530. this._kernelBlurXPostprocess.packedFloat = true;
  59531. this._kernelBlurYPostprocess.packedFloat = true;
  59532. }
  59533. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59534. }
  59535. else {
  59536. 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);
  59537. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59538. effect.setFloat2("screenSize", targetSize, targetSize);
  59539. effect.setTexture("textureSampler", _this._shadowMap);
  59540. });
  59541. this._boxBlurPostprocess.autoClear = false;
  59542. this._blurPostProcesses = [this._boxBlurPostprocess];
  59543. }
  59544. };
  59545. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59546. var index;
  59547. var engine = this._scene.getEngine();
  59548. if (depthOnlySubMeshes.length) {
  59549. engine.setColorWrite(false);
  59550. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59551. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59552. }
  59553. engine.setColorWrite(true);
  59554. }
  59555. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59556. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59557. }
  59558. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59559. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59560. }
  59561. if (this._transparencyShadow) {
  59562. for (index = 0; index < transparentSubMeshes.length; index++) {
  59563. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59564. }
  59565. }
  59566. };
  59567. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59568. var _this = this;
  59569. var mesh = subMesh.getRenderingMesh();
  59570. var scene = this._scene;
  59571. var engine = scene.getEngine();
  59572. var material = subMesh.getMaterial();
  59573. if (!material) {
  59574. return;
  59575. }
  59576. // Culling
  59577. engine.setState(material.backFaceCulling);
  59578. // Managing instances
  59579. var batch = mesh._getInstancesRenderList(subMesh._id);
  59580. if (batch.mustReturn) {
  59581. return;
  59582. }
  59583. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59584. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59585. engine.enableEffect(this._effect);
  59586. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59587. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59588. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59589. this._effect.setVector3("lightPosition", this.getLight().position);
  59590. if (scene.activeCamera) {
  59591. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59592. }
  59593. // Alpha test
  59594. if (material && material.needAlphaTesting()) {
  59595. var alphaTexture = material.getAlphaTestTexture();
  59596. if (alphaTexture) {
  59597. this._effect.setTexture("diffuseSampler", alphaTexture);
  59598. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59599. }
  59600. }
  59601. // Bones
  59602. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59603. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59604. }
  59605. if (this.forceBackFacesOnly) {
  59606. engine.setState(true, 0, false, true);
  59607. }
  59608. // Draw
  59609. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59610. if (this.forceBackFacesOnly) {
  59611. engine.setState(true, 0, false, false);
  59612. }
  59613. }
  59614. else {
  59615. // Need to reset refresh rate of the shadowMap
  59616. if (this._shadowMap) {
  59617. this._shadowMap.resetRefreshCounter();
  59618. }
  59619. }
  59620. };
  59621. ShadowGenerator.prototype._applyFilterValues = function () {
  59622. if (!this._shadowMap) {
  59623. return;
  59624. }
  59625. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59626. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59627. }
  59628. else {
  59629. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59630. }
  59631. };
  59632. /**
  59633. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59634. * @param onCompiled Callback triggered at the and of the effects compilation
  59635. * @param options Sets of optional options forcing the compilation with different modes
  59636. */
  59637. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59638. var _this = this;
  59639. var localOptions = __assign({ useInstances: false }, options);
  59640. var shadowMap = this.getShadowMap();
  59641. if (!shadowMap) {
  59642. if (onCompiled) {
  59643. onCompiled(this);
  59644. }
  59645. return;
  59646. }
  59647. var renderList = shadowMap.renderList;
  59648. if (!renderList) {
  59649. if (onCompiled) {
  59650. onCompiled(this);
  59651. }
  59652. return;
  59653. }
  59654. var subMeshes = new Array();
  59655. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59656. var mesh = renderList_1[_i];
  59657. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59658. }
  59659. if (subMeshes.length === 0) {
  59660. if (onCompiled) {
  59661. onCompiled(this);
  59662. }
  59663. return;
  59664. }
  59665. var currentIndex = 0;
  59666. var checkReady = function () {
  59667. if (!_this._scene || !_this._scene.getEngine()) {
  59668. return;
  59669. }
  59670. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59671. currentIndex++;
  59672. if (currentIndex >= subMeshes.length) {
  59673. if (onCompiled) {
  59674. onCompiled(_this);
  59675. }
  59676. return;
  59677. }
  59678. }
  59679. setTimeout(checkReady, 16);
  59680. };
  59681. checkReady();
  59682. };
  59683. /**
  59684. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59685. * @param options Sets of optional options forcing the compilation with different modes
  59686. * @returns A promise that resolves when the compilation completes
  59687. */
  59688. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59689. var _this = this;
  59690. return new Promise(function (resolve) {
  59691. _this.forceCompilation(function () {
  59692. resolve();
  59693. }, options);
  59694. });
  59695. };
  59696. /**
  59697. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59698. * @param subMesh The submesh we want to render in the shadow map
  59699. * @param useInstances Defines wether will draw in the map using instances
  59700. * @returns true if ready otherwise, false
  59701. */
  59702. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59703. var defines = [];
  59704. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59705. defines.push("#define FLOAT");
  59706. }
  59707. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59708. defines.push("#define ESM");
  59709. }
  59710. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59711. var mesh = subMesh.getMesh();
  59712. var material = subMesh.getMaterial();
  59713. // Alpha test
  59714. if (material && material.needAlphaTesting()) {
  59715. var alphaTexture = material.getAlphaTestTexture();
  59716. if (alphaTexture) {
  59717. defines.push("#define ALPHATEST");
  59718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59719. attribs.push(BABYLON.VertexBuffer.UVKind);
  59720. defines.push("#define UV1");
  59721. }
  59722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59723. if (alphaTexture.coordinatesIndex === 1) {
  59724. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59725. defines.push("#define UV2");
  59726. }
  59727. }
  59728. }
  59729. }
  59730. // Bones
  59731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59734. if (mesh.numBoneInfluencers > 4) {
  59735. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59736. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59737. }
  59738. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59739. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59740. }
  59741. else {
  59742. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59743. }
  59744. // Instances
  59745. if (useInstances) {
  59746. defines.push("#define INSTANCES");
  59747. attribs.push("world0");
  59748. attribs.push("world1");
  59749. attribs.push("world2");
  59750. attribs.push("world3");
  59751. }
  59752. // Get correct effect
  59753. var join = defines.join("\n");
  59754. if (this._cachedDefines !== join) {
  59755. this._cachedDefines = join;
  59756. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59757. }
  59758. if (!this._effect.isReady()) {
  59759. return false;
  59760. }
  59761. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59762. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59763. this._initializeBlurRTTAndPostProcesses();
  59764. }
  59765. }
  59766. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59767. return false;
  59768. }
  59769. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59770. return false;
  59771. }
  59772. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59773. return false;
  59774. }
  59775. return true;
  59776. };
  59777. /**
  59778. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59779. * @param defines Defines of the material we want to update
  59780. * @param lightIndex Index of the light in the enabled light list of the material
  59781. */
  59782. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59783. var scene = this._scene;
  59784. var light = this._light;
  59785. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59786. return;
  59787. }
  59788. defines["SHADOW" + lightIndex] = true;
  59789. if (this.usePoissonSampling) {
  59790. defines["SHADOWPCF" + lightIndex] = true;
  59791. }
  59792. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59793. defines["SHADOWESM" + lightIndex] = true;
  59794. }
  59795. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59796. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59797. }
  59798. if (light.needCube()) {
  59799. defines["SHADOWCUBE" + lightIndex] = true;
  59800. }
  59801. };
  59802. /**
  59803. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59804. * defined in the generator but impacting the effect).
  59805. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59806. * @param effect The effect we are binfing the information for
  59807. */
  59808. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59809. var light = this._light;
  59810. var scene = this._scene;
  59811. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59812. return;
  59813. }
  59814. var camera = scene.activeCamera;
  59815. if (!camera) {
  59816. return;
  59817. }
  59818. var shadowMap = this.getShadowMap();
  59819. if (!shadowMap) {
  59820. return;
  59821. }
  59822. if (!light.needCube()) {
  59823. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59824. }
  59825. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59826. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59827. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59828. };
  59829. /**
  59830. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59831. * (eq to shadow prjection matrix * light transform matrix)
  59832. * @returns The transform matrix used to create the shadow map
  59833. */
  59834. ShadowGenerator.prototype.getTransformMatrix = function () {
  59835. var scene = this._scene;
  59836. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59837. return this._transformMatrix;
  59838. }
  59839. this._currentRenderID = scene.getRenderId();
  59840. this._currentFaceIndexCache = this._currentFaceIndex;
  59841. var lightPosition = this._light.position;
  59842. if (this._light.computeTransformedInformation()) {
  59843. lightPosition = this._light.transformedPosition;
  59844. }
  59845. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59846. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59847. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59848. }
  59849. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59850. this._cachedPosition = lightPosition.clone();
  59851. this._cachedDirection = this._lightDirection.clone();
  59852. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59853. var shadowMap = this.getShadowMap();
  59854. if (shadowMap) {
  59855. var renderList = shadowMap.renderList;
  59856. if (renderList) {
  59857. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59858. }
  59859. }
  59860. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59861. }
  59862. return this._transformMatrix;
  59863. };
  59864. /**
  59865. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59866. * Cube and 2D textures for instance.
  59867. */
  59868. ShadowGenerator.prototype.recreateShadowMap = function () {
  59869. var shadowMap = this._shadowMap;
  59870. if (!shadowMap) {
  59871. return;
  59872. }
  59873. // Track render list.
  59874. var renderList = shadowMap.renderList;
  59875. // Clean up existing data.
  59876. this._disposeRTTandPostProcesses();
  59877. // Reinitializes.
  59878. this._initializeGenerator();
  59879. // Reaffect the filter to ensure a correct fallback if necessary.
  59880. this.filter = this.filter;
  59881. // Reaffect the filter.
  59882. this._applyFilterValues();
  59883. // Reaffect Render List.
  59884. this._shadowMap.renderList = renderList;
  59885. };
  59886. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59887. if (this._shadowMap2) {
  59888. this._shadowMap2.dispose();
  59889. this._shadowMap2 = null;
  59890. }
  59891. if (this._boxBlurPostprocess) {
  59892. this._boxBlurPostprocess.dispose();
  59893. this._boxBlurPostprocess = null;
  59894. }
  59895. if (this._kernelBlurXPostprocess) {
  59896. this._kernelBlurXPostprocess.dispose();
  59897. this._kernelBlurXPostprocess = null;
  59898. }
  59899. if (this._kernelBlurYPostprocess) {
  59900. this._kernelBlurYPostprocess.dispose();
  59901. this._kernelBlurYPostprocess = null;
  59902. }
  59903. this._blurPostProcesses = [];
  59904. };
  59905. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59906. if (this._shadowMap) {
  59907. this._shadowMap.dispose();
  59908. this._shadowMap = null;
  59909. }
  59910. this._disposeBlurPostProcesses();
  59911. };
  59912. /**
  59913. * Disposes the ShadowGenerator.
  59914. * Returns nothing.
  59915. */
  59916. ShadowGenerator.prototype.dispose = function () {
  59917. this._disposeRTTandPostProcesses();
  59918. if (this._light) {
  59919. this._light._shadowGenerator = null;
  59920. this._light._markMeshesAsLightDirty();
  59921. }
  59922. };
  59923. /**
  59924. * Serializes the shadow generator setup to a json object.
  59925. * @returns The serialized JSON object
  59926. */
  59927. ShadowGenerator.prototype.serialize = function () {
  59928. var serializationObject = {};
  59929. var shadowMap = this.getShadowMap();
  59930. if (!shadowMap) {
  59931. return serializationObject;
  59932. }
  59933. serializationObject.lightId = this._light.id;
  59934. serializationObject.mapSize = shadowMap.getRenderSize();
  59935. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59936. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59937. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59938. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59939. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59940. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59941. serializationObject.depthScale = this.depthScale;
  59942. serializationObject.darkness = this.getDarkness();
  59943. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59944. serializationObject.blurKernel = this.blurKernel;
  59945. serializationObject.blurScale = this.blurScale;
  59946. serializationObject.useKernelBlur = this.useKernelBlur;
  59947. serializationObject.transparencyShadow = this._transparencyShadow;
  59948. serializationObject.renderList = [];
  59949. if (shadowMap.renderList) {
  59950. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59951. var mesh = shadowMap.renderList[meshIndex];
  59952. serializationObject.renderList.push(mesh.id);
  59953. }
  59954. }
  59955. return serializationObject;
  59956. };
  59957. /**
  59958. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59959. * @param parsedShadowGenerator The JSON object to parse
  59960. * @param scene The scene to create the shadow map for
  59961. * @returns The parsed shadow generator
  59962. */
  59963. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59964. //casting to point light, as light is missing the position attr and typescript complains.
  59965. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59966. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59967. var shadowMap = shadowGenerator.getShadowMap();
  59968. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59969. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59970. meshes.forEach(function (mesh) {
  59971. if (!shadowMap) {
  59972. return;
  59973. }
  59974. if (!shadowMap.renderList) {
  59975. shadowMap.renderList = [];
  59976. }
  59977. shadowMap.renderList.push(mesh);
  59978. });
  59979. }
  59980. if (parsedShadowGenerator.usePoissonSampling) {
  59981. shadowGenerator.usePoissonSampling = true;
  59982. }
  59983. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59984. shadowGenerator.useExponentialShadowMap = true;
  59985. }
  59986. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59987. shadowGenerator.useBlurExponentialShadowMap = true;
  59988. }
  59989. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59990. shadowGenerator.useCloseExponentialShadowMap = true;
  59991. }
  59992. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59993. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59994. }
  59995. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59996. shadowGenerator.useExponentialShadowMap = true;
  59997. }
  59998. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59999. shadowGenerator.useBlurExponentialShadowMap = true;
  60000. }
  60001. if (parsedShadowGenerator.depthScale) {
  60002. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60003. }
  60004. if (parsedShadowGenerator.blurScale) {
  60005. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60006. }
  60007. if (parsedShadowGenerator.blurBoxOffset) {
  60008. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60009. }
  60010. if (parsedShadowGenerator.useKernelBlur) {
  60011. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60012. }
  60013. if (parsedShadowGenerator.blurKernel) {
  60014. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60015. }
  60016. if (parsedShadowGenerator.bias !== undefined) {
  60017. shadowGenerator.bias = parsedShadowGenerator.bias;
  60018. }
  60019. if (parsedShadowGenerator.darkness) {
  60020. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60021. }
  60022. if (parsedShadowGenerator.transparencyShadow) {
  60023. shadowGenerator.setTransparencyShadow(true);
  60024. }
  60025. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60026. return shadowGenerator;
  60027. };
  60028. ShadowGenerator._FILTER_NONE = 0;
  60029. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60030. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60031. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60032. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60033. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60034. return ShadowGenerator;
  60035. }());
  60036. BABYLON.ShadowGenerator = ShadowGenerator;
  60037. })(BABYLON || (BABYLON = {}));
  60038. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60039. var BABYLON;
  60040. (function (BABYLON) {
  60041. var DefaultLoadingScreen = /** @class */ (function () {
  60042. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60043. if (_loadingText === void 0) { _loadingText = ""; }
  60044. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60045. var _this = this;
  60046. this._renderingCanvas = _renderingCanvas;
  60047. this._loadingText = _loadingText;
  60048. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60049. // Resize
  60050. this._resizeLoadingUI = function () {
  60051. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60052. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60053. if (!_this._loadingDiv) {
  60054. return;
  60055. }
  60056. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60057. _this._loadingDiv.style.left = canvasRect.left + "px";
  60058. _this._loadingDiv.style.top = canvasRect.top + "px";
  60059. _this._loadingDiv.style.width = canvasRect.width + "px";
  60060. _this._loadingDiv.style.height = canvasRect.height + "px";
  60061. };
  60062. }
  60063. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60064. if (this._loadingDiv) {
  60065. // Do not add a loading screen if there is already one
  60066. return;
  60067. }
  60068. this._loadingDiv = document.createElement("div");
  60069. this._loadingDiv.id = "babylonjsLoadingDiv";
  60070. this._loadingDiv.style.opacity = "0";
  60071. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60072. this._loadingDiv.style.pointerEvents = "none";
  60073. // Loading text
  60074. this._loadingTextDiv = document.createElement("div");
  60075. this._loadingTextDiv.style.position = "absolute";
  60076. this._loadingTextDiv.style.left = "0";
  60077. this._loadingTextDiv.style.top = "50%";
  60078. this._loadingTextDiv.style.marginTop = "80px";
  60079. this._loadingTextDiv.style.width = "100%";
  60080. this._loadingTextDiv.style.height = "20px";
  60081. this._loadingTextDiv.style.fontFamily = "Arial";
  60082. this._loadingTextDiv.style.fontSize = "14px";
  60083. this._loadingTextDiv.style.color = "white";
  60084. this._loadingTextDiv.style.textAlign = "center";
  60085. this._loadingTextDiv.innerHTML = "Loading";
  60086. this._loadingDiv.appendChild(this._loadingTextDiv);
  60087. //set the predefined text
  60088. this._loadingTextDiv.innerHTML = this._loadingText;
  60089. // Generating keyframes
  60090. var style = document.createElement('style');
  60091. style.type = 'text/css';
  60092. 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 }";
  60093. style.innerHTML = keyFrames;
  60094. document.getElementsByTagName('head')[0].appendChild(style);
  60095. // Loading img
  60096. var imgBack = new Image();
  60097. 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";
  60098. imgBack.style.position = "absolute";
  60099. imgBack.style.left = "50%";
  60100. imgBack.style.top = "50%";
  60101. imgBack.style.marginLeft = "-60px";
  60102. imgBack.style.marginTop = "-60px";
  60103. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60104. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60105. imgBack.style.transformOrigin = "50% 50%";
  60106. imgBack.style.webkitTransformOrigin = "50% 50%";
  60107. this._loadingDiv.appendChild(imgBack);
  60108. this._resizeLoadingUI();
  60109. window.addEventListener("resize", this._resizeLoadingUI);
  60110. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60111. document.body.appendChild(this._loadingDiv);
  60112. this._loadingDiv.style.opacity = "1";
  60113. };
  60114. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60115. var _this = this;
  60116. if (!this._loadingDiv) {
  60117. return;
  60118. }
  60119. var onTransitionEnd = function () {
  60120. if (!_this._loadingDiv) {
  60121. return;
  60122. }
  60123. document.body.removeChild(_this._loadingDiv);
  60124. window.removeEventListener("resize", _this._resizeLoadingUI);
  60125. _this._loadingDiv = null;
  60126. };
  60127. this._loadingDiv.style.opacity = "0";
  60128. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60129. };
  60130. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60131. set: function (text) {
  60132. this._loadingText = text;
  60133. if (this._loadingTextDiv) {
  60134. this._loadingTextDiv.innerHTML = this._loadingText;
  60135. }
  60136. },
  60137. enumerable: true,
  60138. configurable: true
  60139. });
  60140. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60141. get: function () {
  60142. return this._loadingDivBackgroundColor;
  60143. },
  60144. set: function (color) {
  60145. this._loadingDivBackgroundColor = color;
  60146. if (!this._loadingDiv) {
  60147. return;
  60148. }
  60149. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60150. },
  60151. enumerable: true,
  60152. configurable: true
  60153. });
  60154. return DefaultLoadingScreen;
  60155. }());
  60156. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60157. })(BABYLON || (BABYLON = {}));
  60158. //# sourceMappingURL=babylon.loadingScreen.js.map
  60159. var BABYLON;
  60160. (function (BABYLON) {
  60161. var SceneLoaderProgressEvent = /** @class */ (function () {
  60162. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60163. this.lengthComputable = lengthComputable;
  60164. this.loaded = loaded;
  60165. this.total = total;
  60166. }
  60167. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60168. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60169. };
  60170. return SceneLoaderProgressEvent;
  60171. }());
  60172. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60173. var SceneLoader = /** @class */ (function () {
  60174. function SceneLoader() {
  60175. }
  60176. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60177. get: function () {
  60178. return 0;
  60179. },
  60180. enumerable: true,
  60181. configurable: true
  60182. });
  60183. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60184. get: function () {
  60185. return 1;
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60191. get: function () {
  60192. return 2;
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60198. get: function () {
  60199. return 3;
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60205. get: function () {
  60206. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60207. },
  60208. set: function (value) {
  60209. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60210. },
  60211. enumerable: true,
  60212. configurable: true
  60213. });
  60214. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60215. get: function () {
  60216. return SceneLoader._ShowLoadingScreen;
  60217. },
  60218. set: function (value) {
  60219. SceneLoader._ShowLoadingScreen = value;
  60220. },
  60221. enumerable: true,
  60222. configurable: true
  60223. });
  60224. Object.defineProperty(SceneLoader, "loggingLevel", {
  60225. get: function () {
  60226. return SceneLoader._loggingLevel;
  60227. },
  60228. set: function (value) {
  60229. SceneLoader._loggingLevel = value;
  60230. },
  60231. enumerable: true,
  60232. configurable: true
  60233. });
  60234. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60235. get: function () {
  60236. return SceneLoader._CleanBoneMatrixWeights;
  60237. },
  60238. set: function (value) {
  60239. SceneLoader._CleanBoneMatrixWeights = value;
  60240. },
  60241. enumerable: true,
  60242. configurable: true
  60243. });
  60244. SceneLoader._getDefaultPlugin = function () {
  60245. return SceneLoader._registeredPlugins[".babylon"];
  60246. };
  60247. SceneLoader._getPluginForExtension = function (extension) {
  60248. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60249. if (registeredPlugin) {
  60250. return registeredPlugin;
  60251. }
  60252. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60253. return SceneLoader._getDefaultPlugin();
  60254. };
  60255. SceneLoader._getPluginForDirectLoad = function (data) {
  60256. for (var extension in SceneLoader._registeredPlugins) {
  60257. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60258. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60259. return SceneLoader._registeredPlugins[extension];
  60260. }
  60261. }
  60262. return SceneLoader._getDefaultPlugin();
  60263. };
  60264. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60265. if (sceneFilename.name) {
  60266. sceneFilename = sceneFilename.name;
  60267. }
  60268. var queryStringPosition = sceneFilename.indexOf("?");
  60269. if (queryStringPosition !== -1) {
  60270. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60271. }
  60272. var dotPosition = sceneFilename.lastIndexOf(".");
  60273. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60274. return SceneLoader._getPluginForExtension(extension);
  60275. };
  60276. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60277. SceneLoader._getDirectLoad = function (sceneFilename) {
  60278. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60279. return sceneFilename.substr(5);
  60280. }
  60281. return null;
  60282. };
  60283. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60284. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60285. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60286. var plugin;
  60287. if (registeredPlugin.plugin.createPlugin) {
  60288. plugin = registeredPlugin.plugin.createPlugin();
  60289. }
  60290. else {
  60291. plugin = registeredPlugin.plugin;
  60292. }
  60293. var useArrayBuffer = registeredPlugin.isBinary;
  60294. var database;
  60295. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60296. var dataCallback = function (data, responseURL) {
  60297. if (scene.isDisposed) {
  60298. onError("Scene has been disposed");
  60299. return;
  60300. }
  60301. scene.database = database;
  60302. onSuccess(plugin, data, responseURL);
  60303. };
  60304. var request = null;
  60305. var pluginDisposed = false;
  60306. var onDisposeObservable = plugin.onDisposeObservable;
  60307. if (onDisposeObservable) {
  60308. onDisposeObservable.add(function () {
  60309. pluginDisposed = true;
  60310. if (request) {
  60311. request.abort();
  60312. request = null;
  60313. }
  60314. onDispose();
  60315. });
  60316. }
  60317. var manifestChecked = function () {
  60318. if (pluginDisposed) {
  60319. return;
  60320. }
  60321. var url = rootUrl + sceneFilename;
  60322. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60323. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60324. } : undefined, database, useArrayBuffer, function (request, exception) {
  60325. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60326. });
  60327. };
  60328. if (directLoad) {
  60329. dataCallback(directLoad);
  60330. return plugin;
  60331. }
  60332. if (rootUrl.indexOf("file:") === -1) {
  60333. if (scene.getEngine().enableOfflineSupport) {
  60334. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60335. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60336. }
  60337. else {
  60338. manifestChecked();
  60339. }
  60340. }
  60341. else {
  60342. var fileOrString = sceneFilename;
  60343. if (fileOrString.name) {
  60344. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60345. }
  60346. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60347. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60348. }
  60349. else {
  60350. onError("Unable to find file named " + sceneFilename);
  60351. }
  60352. }
  60353. return plugin;
  60354. };
  60355. // Public functions
  60356. SceneLoader.GetPluginForExtension = function (extension) {
  60357. return SceneLoader._getPluginForExtension(extension).plugin;
  60358. };
  60359. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60360. return !!SceneLoader._registeredPlugins[extension];
  60361. };
  60362. SceneLoader.RegisterPlugin = function (plugin) {
  60363. if (typeof plugin.extensions === "string") {
  60364. var extension = plugin.extensions;
  60365. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60366. plugin: plugin,
  60367. isBinary: false
  60368. };
  60369. }
  60370. else {
  60371. var extensions = plugin.extensions;
  60372. Object.keys(extensions).forEach(function (extension) {
  60373. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60374. plugin: plugin,
  60375. isBinary: extensions[extension].isBinary
  60376. };
  60377. });
  60378. }
  60379. };
  60380. /**
  60381. * Import meshes into a scene
  60382. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60383. * @param rootUrl a string that defines the root url for scene and resources
  60384. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60385. * @param scene the instance of BABYLON.Scene to append to
  60386. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60387. * @param onProgress a callback with a progress event for each file being loaded
  60388. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60389. * @param pluginExtension the extension used to determine the plugin
  60390. * @returns The loaded plugin
  60391. */
  60392. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60393. if (onSuccess === void 0) { onSuccess = null; }
  60394. if (onProgress === void 0) { onProgress = null; }
  60395. if (onError === void 0) { onError = null; }
  60396. if (pluginExtension === void 0) { pluginExtension = null; }
  60397. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60398. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60399. return null;
  60400. }
  60401. var loadingToken = {};
  60402. scene._addPendingData(loadingToken);
  60403. var disposeHandler = function () {
  60404. scene._removePendingData(loadingToken);
  60405. };
  60406. var errorHandler = function (message, exception) {
  60407. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60408. if (onError) {
  60409. onError(scene, errorMessage, exception);
  60410. }
  60411. else {
  60412. BABYLON.Tools.Error(errorMessage);
  60413. // should the exception be thrown?
  60414. }
  60415. disposeHandler();
  60416. };
  60417. var progressHandler = onProgress ? function (event) {
  60418. try {
  60419. onProgress(event);
  60420. }
  60421. catch (e) {
  60422. errorHandler("Error in onProgress callback", e);
  60423. }
  60424. } : undefined;
  60425. var successHandler = function (meshes, particleSystems, skeletons) {
  60426. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60427. if (onSuccess) {
  60428. try {
  60429. onSuccess(meshes, particleSystems, skeletons);
  60430. }
  60431. catch (e) {
  60432. errorHandler("Error in onSuccess callback", e);
  60433. }
  60434. }
  60435. scene._removePendingData(loadingToken);
  60436. };
  60437. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60438. if (plugin.rewriteRootURL) {
  60439. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60440. }
  60441. if (sceneFilename === "") {
  60442. if (sceneFilename === "") {
  60443. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60444. }
  60445. }
  60446. if (plugin.importMesh) {
  60447. var syncedPlugin = plugin;
  60448. var meshes = new Array();
  60449. var particleSystems = new Array();
  60450. var skeletons = new Array();
  60451. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60452. return;
  60453. }
  60454. scene.loadingPluginName = plugin.name;
  60455. successHandler(meshes, particleSystems, skeletons);
  60456. }
  60457. else {
  60458. var asyncedPlugin = plugin;
  60459. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60460. scene.loadingPluginName = plugin.name;
  60461. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60462. }).catch(function (error) {
  60463. errorHandler(error.message, error);
  60464. });
  60465. }
  60466. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60467. };
  60468. /**
  60469. * Import meshes into a scene
  60470. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60471. * @param rootUrl a string that defines the root url for scene and resources
  60472. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60473. * @param scene the instance of BABYLON.Scene to append to
  60474. * @param onProgress a callback with a progress event for each file being loaded
  60475. * @param pluginExtension the extension used to determine the plugin
  60476. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60477. */
  60478. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60479. if (onProgress === void 0) { onProgress = null; }
  60480. if (pluginExtension === void 0) { pluginExtension = null; }
  60481. return new Promise(function (resolve, reject) {
  60482. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60483. resolve({
  60484. meshes: meshes,
  60485. particleSystems: particleSystems,
  60486. skeletons: skeletons
  60487. });
  60488. }, onProgress, function (scene, message, exception) {
  60489. reject(exception || new Error(message));
  60490. });
  60491. });
  60492. };
  60493. /**
  60494. * Load a scene
  60495. * @param rootUrl a string that defines the root url for scene and resources
  60496. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60497. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60498. * @param onSuccess a callback with the scene when import succeeds
  60499. * @param onProgress a callback with a progress event for each file being loaded
  60500. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60501. * @param pluginExtension the extension used to determine the plugin
  60502. * @returns The loaded plugin
  60503. */
  60504. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60505. if (onSuccess === void 0) { onSuccess = null; }
  60506. if (onProgress === void 0) { onProgress = null; }
  60507. if (onError === void 0) { onError = null; }
  60508. if (pluginExtension === void 0) { pluginExtension = null; }
  60509. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60510. };
  60511. /**
  60512. * Load a scene
  60513. * @param rootUrl a string that defines the root url for scene and resources
  60514. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60515. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60516. * @param onProgress a callback with a progress event for each file being loaded
  60517. * @param pluginExtension the extension used to determine the plugin
  60518. * @returns The loaded scene
  60519. */
  60520. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60521. if (onProgress === void 0) { onProgress = null; }
  60522. if (pluginExtension === void 0) { pluginExtension = null; }
  60523. return new Promise(function (resolve, reject) {
  60524. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60525. resolve(scene);
  60526. }, onProgress, function (scene, message, exception) {
  60527. reject(exception || new Error(message));
  60528. }, pluginExtension);
  60529. });
  60530. };
  60531. /**
  60532. * Append a scene
  60533. * @param rootUrl a string that defines the root url for scene and resources
  60534. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60535. * @param scene is the instance of BABYLON.Scene to append to
  60536. * @param onSuccess a callback with the scene when import succeeds
  60537. * @param onProgress a callback with a progress event for each file being loaded
  60538. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60539. * @param pluginExtension the extension used to determine the plugin
  60540. * @returns The loaded plugin
  60541. */
  60542. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60543. if (onSuccess === void 0) { onSuccess = null; }
  60544. if (onProgress === void 0) { onProgress = null; }
  60545. if (onError === void 0) { onError = null; }
  60546. if (pluginExtension === void 0) { pluginExtension = null; }
  60547. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60548. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60549. return null;
  60550. }
  60551. if (SceneLoader.ShowLoadingScreen) {
  60552. scene.getEngine().displayLoadingUI();
  60553. }
  60554. var loadingToken = {};
  60555. scene._addPendingData(loadingToken);
  60556. var disposeHandler = function () {
  60557. scene._removePendingData(loadingToken);
  60558. scene.getEngine().hideLoadingUI();
  60559. };
  60560. var errorHandler = function (message, exception) {
  60561. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60562. if (onError) {
  60563. onError(scene, errorMessage, exception);
  60564. }
  60565. else {
  60566. BABYLON.Tools.Error(errorMessage);
  60567. // should the exception be thrown?
  60568. }
  60569. disposeHandler();
  60570. };
  60571. var progressHandler = onProgress ? function (event) {
  60572. try {
  60573. onProgress(event);
  60574. }
  60575. catch (e) {
  60576. errorHandler("Error in onProgress callback", e);
  60577. }
  60578. } : undefined;
  60579. var successHandler = function () {
  60580. if (onSuccess) {
  60581. try {
  60582. onSuccess(scene);
  60583. }
  60584. catch (e) {
  60585. errorHandler("Error in onSuccess callback", e);
  60586. }
  60587. }
  60588. scene._removePendingData(loadingToken);
  60589. };
  60590. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60591. if (sceneFilename === "") {
  60592. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60593. }
  60594. if (plugin.load) {
  60595. var syncedPlugin = plugin;
  60596. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60597. return;
  60598. }
  60599. scene.loadingPluginName = plugin.name;
  60600. successHandler();
  60601. }
  60602. else {
  60603. var asyncedPlugin = plugin;
  60604. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60605. scene.loadingPluginName = plugin.name;
  60606. successHandler();
  60607. }).catch(function (error) {
  60608. errorHandler(error.message, error);
  60609. });
  60610. }
  60611. if (SceneLoader.ShowLoadingScreen) {
  60612. scene.executeWhenReady(function () {
  60613. scene.getEngine().hideLoadingUI();
  60614. });
  60615. }
  60616. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60617. };
  60618. /**
  60619. * Append a scene
  60620. * @param rootUrl a string that defines the root url for scene and resources
  60621. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60622. * @param scene is the instance of BABYLON.Scene to append to
  60623. * @param onProgress a callback with a progress event for each file being loaded
  60624. * @param pluginExtension the extension used to determine the plugin
  60625. * @returns The given scene
  60626. */
  60627. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60628. if (onProgress === void 0) { onProgress = null; }
  60629. if (pluginExtension === void 0) { pluginExtension = null; }
  60630. return new Promise(function (resolve, reject) {
  60631. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60632. resolve(scene);
  60633. }, onProgress, function (scene, message, exception) {
  60634. reject(exception || new Error(message));
  60635. }, pluginExtension);
  60636. });
  60637. };
  60638. /**
  60639. * Load a scene into an asset container
  60640. * @param rootUrl a string that defines the root url for scene and resources
  60641. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60642. * @param scene is the instance of BABYLON.Scene to append to
  60643. * @param onSuccess a callback with the scene when import succeeds
  60644. * @param onProgress a callback with a progress event for each file being loaded
  60645. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60646. * @param pluginExtension the extension used to determine the plugin
  60647. * @returns The loaded plugin
  60648. */
  60649. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60650. if (onSuccess === void 0) { onSuccess = null; }
  60651. if (onProgress === void 0) { onProgress = null; }
  60652. if (onError === void 0) { onError = null; }
  60653. if (pluginExtension === void 0) { pluginExtension = null; }
  60654. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60655. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60656. return null;
  60657. }
  60658. var loadingToken = {};
  60659. scene._addPendingData(loadingToken);
  60660. var disposeHandler = function () {
  60661. scene._removePendingData(loadingToken);
  60662. };
  60663. var errorHandler = function (message, exception) {
  60664. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60665. if (onError) {
  60666. onError(scene, errorMessage, exception);
  60667. }
  60668. else {
  60669. BABYLON.Tools.Error(errorMessage);
  60670. // should the exception be thrown?
  60671. }
  60672. disposeHandler();
  60673. };
  60674. var progressHandler = onProgress ? function (event) {
  60675. try {
  60676. onProgress(event);
  60677. }
  60678. catch (e) {
  60679. errorHandler("Error in onProgress callback", e);
  60680. }
  60681. } : undefined;
  60682. var successHandler = function (assets) {
  60683. if (onSuccess) {
  60684. try {
  60685. onSuccess(assets);
  60686. }
  60687. catch (e) {
  60688. errorHandler("Error in onSuccess callback", e);
  60689. }
  60690. }
  60691. scene._removePendingData(loadingToken);
  60692. };
  60693. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60694. if (plugin.loadAssetContainer) {
  60695. var syncedPlugin = plugin;
  60696. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60697. if (!assetContainer) {
  60698. return;
  60699. }
  60700. scene.loadingPluginName = plugin.name;
  60701. successHandler(assetContainer);
  60702. }
  60703. else if (plugin.loadAssetContainerAsync) {
  60704. var asyncedPlugin = plugin;
  60705. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60706. scene.loadingPluginName = plugin.name;
  60707. successHandler(assetContainer);
  60708. }).catch(function (error) {
  60709. errorHandler(error.message, error);
  60710. });
  60711. }
  60712. else {
  60713. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60714. }
  60715. if (SceneLoader.ShowLoadingScreen) {
  60716. scene.executeWhenReady(function () {
  60717. scene.getEngine().hideLoadingUI();
  60718. });
  60719. }
  60720. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60721. };
  60722. /**
  60723. * Load a scene into an asset container
  60724. * @param rootUrl a string that defines the root url for scene and resources
  60725. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60726. * @param scene is the instance of BABYLON.Scene to append to
  60727. * @param onProgress a callback with a progress event for each file being loaded
  60728. * @param pluginExtension the extension used to determine the plugin
  60729. * @returns The loaded asset container
  60730. */
  60731. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60732. if (onProgress === void 0) { onProgress = null; }
  60733. if (pluginExtension === void 0) { pluginExtension = null; }
  60734. return new Promise(function (resolve, reject) {
  60735. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60736. resolve(assetContainer);
  60737. }, onProgress, function (scene, message, exception) {
  60738. reject(exception || new Error(message));
  60739. }, pluginExtension);
  60740. });
  60741. };
  60742. // Flags
  60743. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60744. SceneLoader._ShowLoadingScreen = true;
  60745. SceneLoader._CleanBoneMatrixWeights = false;
  60746. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60747. // Members
  60748. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60749. SceneLoader._registeredPlugins = {};
  60750. return SceneLoader;
  60751. }());
  60752. BABYLON.SceneLoader = SceneLoader;
  60753. ;
  60754. })(BABYLON || (BABYLON = {}));
  60755. //# sourceMappingURL=babylon.sceneLoader.js.map
  60756. var BABYLON;
  60757. (function (BABYLON) {
  60758. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60759. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60760. var parsedMaterial = parsedData.materials[index];
  60761. if (parsedMaterial.id === id) {
  60762. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60763. }
  60764. }
  60765. return null;
  60766. };
  60767. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60768. for (var i in names) {
  60769. if (mesh.name === names[i]) {
  60770. hierarchyIds.push(mesh.id);
  60771. return true;
  60772. }
  60773. }
  60774. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60775. hierarchyIds.push(mesh.id);
  60776. return true;
  60777. }
  60778. return false;
  60779. };
  60780. var logOperation = function (operation, producer) {
  60781. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60782. };
  60783. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60784. if (addToScene === void 0) { addToScene = false; }
  60785. var container = new BABYLON.AssetContainer(scene);
  60786. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60787. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60788. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60789. // and avoid problems with multiple concurrent .babylon loads.
  60790. var log = "importScene has failed JSON parse";
  60791. try {
  60792. var parsedData = JSON.parse(data);
  60793. log = "";
  60794. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60795. var index;
  60796. var cache;
  60797. // Lights
  60798. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60799. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60800. var parsedLight = parsedData.lights[index];
  60801. var light = BABYLON.Light.Parse(parsedLight, scene);
  60802. if (light) {
  60803. container.lights.push(light);
  60804. log += (index === 0 ? "\n\tLights:" : "");
  60805. log += "\n\t\t" + light.toString(fullDetails);
  60806. }
  60807. }
  60808. }
  60809. // Animations
  60810. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60811. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60812. var parsedAnimation = parsedData.animations[index];
  60813. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60814. scene.animations.push(animation);
  60815. container.animations.push(animation);
  60816. log += (index === 0 ? "\n\tAnimations:" : "");
  60817. log += "\n\t\t" + animation.toString(fullDetails);
  60818. }
  60819. }
  60820. // Materials
  60821. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60822. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60823. var parsedMaterial = parsedData.materials[index];
  60824. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60825. container.materials.push(mat);
  60826. log += (index === 0 ? "\n\tMaterials:" : "");
  60827. log += "\n\t\t" + mat.toString(fullDetails);
  60828. }
  60829. }
  60830. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60831. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60832. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60833. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60834. container.multiMaterials.push(mmat);
  60835. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60836. log += "\n\t\t" + mmat.toString(fullDetails);
  60837. }
  60838. }
  60839. // Morph targets
  60840. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60841. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60842. var managerData = _a[_i];
  60843. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60844. }
  60845. }
  60846. // Skeletons
  60847. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60848. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60849. var parsedSkeleton = parsedData.skeletons[index];
  60850. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60851. container.skeletons.push(skeleton);
  60852. log += (index === 0 ? "\n\tSkeletons:" : "");
  60853. log += "\n\t\t" + skeleton.toString(fullDetails);
  60854. }
  60855. }
  60856. // Geometries
  60857. var geometries = parsedData.geometries;
  60858. if (geometries !== undefined && geometries !== null) {
  60859. var addedGeometry = new Array();
  60860. // Boxes
  60861. var boxes = geometries.boxes;
  60862. if (boxes !== undefined && boxes !== null) {
  60863. for (index = 0, cache = boxes.length; index < cache; index++) {
  60864. var parsedBox = boxes[index];
  60865. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60866. }
  60867. }
  60868. // Spheres
  60869. var spheres = geometries.spheres;
  60870. if (spheres !== undefined && spheres !== null) {
  60871. for (index = 0, cache = spheres.length; index < cache; index++) {
  60872. var parsedSphere = spheres[index];
  60873. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60874. }
  60875. }
  60876. // Cylinders
  60877. var cylinders = geometries.cylinders;
  60878. if (cylinders !== undefined && cylinders !== null) {
  60879. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60880. var parsedCylinder = cylinders[index];
  60881. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60882. }
  60883. }
  60884. // Toruses
  60885. var toruses = geometries.toruses;
  60886. if (toruses !== undefined && toruses !== null) {
  60887. for (index = 0, cache = toruses.length; index < cache; index++) {
  60888. var parsedTorus = toruses[index];
  60889. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60890. }
  60891. }
  60892. // Grounds
  60893. var grounds = geometries.grounds;
  60894. if (grounds !== undefined && grounds !== null) {
  60895. for (index = 0, cache = grounds.length; index < cache; index++) {
  60896. var parsedGround = grounds[index];
  60897. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60898. }
  60899. }
  60900. // Planes
  60901. var planes = geometries.planes;
  60902. if (planes !== undefined && planes !== null) {
  60903. for (index = 0, cache = planes.length; index < cache; index++) {
  60904. var parsedPlane = planes[index];
  60905. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60906. }
  60907. }
  60908. // TorusKnots
  60909. var torusKnots = geometries.torusKnots;
  60910. if (torusKnots !== undefined && torusKnots !== null) {
  60911. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60912. var parsedTorusKnot = torusKnots[index];
  60913. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60914. }
  60915. }
  60916. // VertexData
  60917. var vertexData = geometries.vertexData;
  60918. if (vertexData !== undefined && vertexData !== null) {
  60919. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60920. var parsedVertexData = vertexData[index];
  60921. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60922. }
  60923. }
  60924. addedGeometry.forEach(function (g) {
  60925. if (g) {
  60926. container.geometries.push(g);
  60927. }
  60928. });
  60929. }
  60930. // Transform nodes
  60931. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60932. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60933. var parsedTransformNode = parsedData.transformNodes[index];
  60934. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60935. container.transformNodes.push(node);
  60936. }
  60937. }
  60938. // Meshes
  60939. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60940. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60941. var parsedMesh = parsedData.meshes[index];
  60942. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60943. container.meshes.push(mesh);
  60944. log += (index === 0 ? "\n\tMeshes:" : "");
  60945. log += "\n\t\t" + mesh.toString(fullDetails);
  60946. }
  60947. }
  60948. // Cameras
  60949. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60950. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60951. var parsedCamera = parsedData.cameras[index];
  60952. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60953. container.cameras.push(camera);
  60954. log += (index === 0 ? "\n\tCameras:" : "");
  60955. log += "\n\t\t" + camera.toString(fullDetails);
  60956. }
  60957. }
  60958. // Browsing all the graph to connect the dots
  60959. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60960. var camera = scene.cameras[index];
  60961. if (camera._waitingParentId) {
  60962. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60963. camera._waitingParentId = null;
  60964. }
  60965. }
  60966. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60967. var light_1 = scene.lights[index];
  60968. if (light_1 && light_1._waitingParentId) {
  60969. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60970. light_1._waitingParentId = null;
  60971. }
  60972. }
  60973. // Sounds
  60974. // TODO: add sound
  60975. var loadedSounds = [];
  60976. var loadedSound;
  60977. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60978. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60979. var parsedSound = parsedData.sounds[index];
  60980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60981. if (!parsedSound.url)
  60982. parsedSound.url = parsedSound.name;
  60983. if (!loadedSounds[parsedSound.url]) {
  60984. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60985. loadedSounds[parsedSound.url] = loadedSound;
  60986. container.sounds.push(loadedSound);
  60987. }
  60988. else {
  60989. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60990. }
  60991. }
  60992. else {
  60993. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60994. }
  60995. }
  60996. }
  60997. loadedSounds = [];
  60998. // Connect parents & children and parse actions
  60999. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61000. var transformNode = scene.transformNodes[index];
  61001. if (transformNode._waitingParentId) {
  61002. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61003. transformNode._waitingParentId = null;
  61004. }
  61005. }
  61006. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61007. var mesh = scene.meshes[index];
  61008. if (mesh._waitingParentId) {
  61009. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61010. mesh._waitingParentId = null;
  61011. }
  61012. if (mesh._waitingActions) {
  61013. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61014. mesh._waitingActions = null;
  61015. }
  61016. }
  61017. // freeze world matrix application
  61018. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61019. var currentMesh = scene.meshes[index];
  61020. if (currentMesh._waitingFreezeWorldMatrix) {
  61021. currentMesh.freezeWorldMatrix();
  61022. currentMesh._waitingFreezeWorldMatrix = null;
  61023. }
  61024. else {
  61025. currentMesh.computeWorldMatrix(true);
  61026. }
  61027. }
  61028. // Particles Systems
  61029. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61030. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61031. var parsedParticleSystem = parsedData.particleSystems[index];
  61032. if (parsedParticleSystem.activeParticleCount) {
  61033. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61034. container.particleSystems.push(ps);
  61035. }
  61036. else {
  61037. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61038. container.particleSystems.push(ps);
  61039. }
  61040. }
  61041. }
  61042. // Lens flares
  61043. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61044. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61045. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61046. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61047. container.lensFlareSystems.push(lf);
  61048. }
  61049. }
  61050. // Shadows
  61051. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61052. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61053. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61054. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61055. container.shadowGenerators.push(sg);
  61056. }
  61057. }
  61058. // Lights exclusions / inclusions
  61059. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61060. var light_2 = scene.lights[index];
  61061. // Excluded check
  61062. if (light_2._excludedMeshesIds.length > 0) {
  61063. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61064. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61065. if (excludedMesh) {
  61066. light_2.excludedMeshes.push(excludedMesh);
  61067. }
  61068. }
  61069. light_2._excludedMeshesIds = [];
  61070. }
  61071. // Included check
  61072. if (light_2._includedOnlyMeshesIds.length > 0) {
  61073. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61074. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61075. if (includedOnlyMesh) {
  61076. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61077. }
  61078. }
  61079. light_2._includedOnlyMeshesIds = [];
  61080. }
  61081. }
  61082. // Actions (scene)
  61083. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61084. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61085. }
  61086. if (!addToScene) {
  61087. container.removeAllFromScene();
  61088. }
  61089. }
  61090. catch (err) {
  61091. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61092. if (onError) {
  61093. onError(msg, err);
  61094. }
  61095. else {
  61096. BABYLON.Tools.Log(msg);
  61097. throw err;
  61098. }
  61099. }
  61100. finally {
  61101. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61102. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61103. }
  61104. }
  61105. return container;
  61106. };
  61107. BABYLON.SceneLoader.RegisterPlugin({
  61108. name: "babylon.js",
  61109. extensions: ".babylon",
  61110. canDirectLoad: function (data) {
  61111. if (data.indexOf("babylon") !== -1) {
  61112. return true;
  61113. }
  61114. return false;
  61115. },
  61116. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61117. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61118. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61119. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61120. // and avoid problems with multiple concurrent .babylon loads.
  61121. var log = "importMesh has failed JSON parse";
  61122. try {
  61123. var parsedData = JSON.parse(data);
  61124. log = "";
  61125. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61126. if (!meshesNames) {
  61127. meshesNames = null;
  61128. }
  61129. else if (!Array.isArray(meshesNames)) {
  61130. meshesNames = [meshesNames];
  61131. }
  61132. var hierarchyIds = new Array();
  61133. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61134. var loadedSkeletonsIds = [];
  61135. var loadedMaterialsIds = [];
  61136. var index;
  61137. var cache;
  61138. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61139. var parsedMesh = parsedData.meshes[index];
  61140. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61141. if (meshesNames !== null) {
  61142. // Remove found mesh name from list.
  61143. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61144. }
  61145. //Geometry?
  61146. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61147. //does the file contain geometries?
  61148. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61149. //find the correct geometry and add it to the scene
  61150. var found = false;
  61151. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61152. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61153. return;
  61154. }
  61155. else {
  61156. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61157. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61158. switch (geometryType) {
  61159. case "boxes":
  61160. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61161. break;
  61162. case "spheres":
  61163. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61164. break;
  61165. case "cylinders":
  61166. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61167. break;
  61168. case "toruses":
  61169. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61170. break;
  61171. case "grounds":
  61172. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61173. break;
  61174. case "planes":
  61175. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61176. break;
  61177. case "torusKnots":
  61178. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61179. break;
  61180. case "vertexData":
  61181. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61182. break;
  61183. }
  61184. found = true;
  61185. }
  61186. });
  61187. }
  61188. });
  61189. if (found === false) {
  61190. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61191. }
  61192. }
  61193. }
  61194. // Material ?
  61195. if (parsedMesh.materialId) {
  61196. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61197. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61198. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61199. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61200. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61201. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61202. var subMatId = parsedMultiMaterial.materials[matIndex];
  61203. loadedMaterialsIds.push(subMatId);
  61204. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61205. if (mat) {
  61206. log += "\n\tMaterial " + mat.toString(fullDetails);
  61207. }
  61208. }
  61209. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61210. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61211. if (mmat) {
  61212. materialFound = true;
  61213. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61214. }
  61215. break;
  61216. }
  61217. }
  61218. }
  61219. if (materialFound === false) {
  61220. loadedMaterialsIds.push(parsedMesh.materialId);
  61221. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61222. if (!mat) {
  61223. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61224. }
  61225. else {
  61226. log += "\n\tMaterial " + mat.toString(fullDetails);
  61227. }
  61228. }
  61229. }
  61230. // Skeleton ?
  61231. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61232. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61233. if (skeletonAlreadyLoaded === false) {
  61234. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61235. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61236. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61237. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61238. skeletons.push(skeleton);
  61239. loadedSkeletonsIds.push(parsedSkeleton.id);
  61240. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61241. }
  61242. }
  61243. }
  61244. }
  61245. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61246. meshes.push(mesh);
  61247. log += "\n\tMesh " + mesh.toString(fullDetails);
  61248. }
  61249. }
  61250. // Connecting parents
  61251. var currentMesh;
  61252. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61253. currentMesh = scene.meshes[index];
  61254. if (currentMesh._waitingParentId) {
  61255. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61256. currentMesh._waitingParentId = null;
  61257. }
  61258. }
  61259. // freeze and compute world matrix application
  61260. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61261. currentMesh = scene.meshes[index];
  61262. if (currentMesh._waitingFreezeWorldMatrix) {
  61263. currentMesh.freezeWorldMatrix();
  61264. currentMesh._waitingFreezeWorldMatrix = null;
  61265. }
  61266. else {
  61267. currentMesh.computeWorldMatrix(true);
  61268. }
  61269. }
  61270. }
  61271. // Particles
  61272. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61273. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61274. var parsedParticleSystem = parsedData.particleSystems[index];
  61275. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61276. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61277. }
  61278. }
  61279. }
  61280. return true;
  61281. }
  61282. catch (err) {
  61283. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61284. if (onError) {
  61285. onError(msg, err);
  61286. }
  61287. else {
  61288. BABYLON.Tools.Log(msg);
  61289. throw err;
  61290. }
  61291. }
  61292. finally {
  61293. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61294. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61295. }
  61296. }
  61297. return false;
  61298. },
  61299. load: function (scene, data, rootUrl, onError) {
  61300. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61301. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61302. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61303. // and avoid problems with multiple concurrent .babylon loads.
  61304. var log = "importScene has failed JSON parse";
  61305. try {
  61306. var parsedData = JSON.parse(data);
  61307. log = "";
  61308. // Scene
  61309. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61310. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61311. }
  61312. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61313. scene.autoClear = parsedData.autoClear;
  61314. }
  61315. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61316. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61317. }
  61318. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61319. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61320. }
  61321. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61322. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61323. }
  61324. // Fog
  61325. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61326. scene.fogMode = parsedData.fogMode;
  61327. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61328. scene.fogStart = parsedData.fogStart;
  61329. scene.fogEnd = parsedData.fogEnd;
  61330. scene.fogDensity = parsedData.fogDensity;
  61331. log += "\tFog mode for scene: ";
  61332. switch (scene.fogMode) {
  61333. // getters not compiling, so using hardcoded
  61334. case 1:
  61335. log += "exp\n";
  61336. break;
  61337. case 2:
  61338. log += "exp2\n";
  61339. break;
  61340. case 3:
  61341. log += "linear\n";
  61342. break;
  61343. }
  61344. }
  61345. //Physics
  61346. if (parsedData.physicsEnabled) {
  61347. var physicsPlugin;
  61348. if (parsedData.physicsEngine === "cannon") {
  61349. physicsPlugin = new BABYLON.CannonJSPlugin();
  61350. }
  61351. else if (parsedData.physicsEngine === "oimo") {
  61352. physicsPlugin = new BABYLON.OimoJSPlugin();
  61353. }
  61354. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61355. //else - default engine, which is currently oimo
  61356. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61357. scene.enablePhysics(physicsGravity, physicsPlugin);
  61358. }
  61359. // Metadata
  61360. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61361. scene.metadata = parsedData.metadata;
  61362. }
  61363. //collisions, if defined. otherwise, default is true
  61364. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61365. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61366. }
  61367. scene.workerCollisions = !!parsedData.workerCollisions;
  61368. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61369. if (!container) {
  61370. return false;
  61371. }
  61372. if (parsedData.autoAnimate) {
  61373. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61374. }
  61375. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61376. scene.setActiveCameraByID(parsedData.activeCameraID);
  61377. }
  61378. // Environment texture
  61379. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61380. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61381. if (parsedData.createDefaultSkybox === true) {
  61382. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61383. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61384. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61385. }
  61386. }
  61387. // Finish
  61388. return true;
  61389. }
  61390. catch (err) {
  61391. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61392. if (onError) {
  61393. onError(msg, err);
  61394. }
  61395. else {
  61396. BABYLON.Tools.Log(msg);
  61397. throw err;
  61398. }
  61399. }
  61400. finally {
  61401. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61402. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61403. }
  61404. }
  61405. return false;
  61406. },
  61407. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61408. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61409. return container;
  61410. }
  61411. });
  61412. })(BABYLON || (BABYLON = {}));
  61413. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61414. var BABYLON;
  61415. (function (BABYLON) {
  61416. var FilesInput = /** @class */ (function () {
  61417. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61418. this.onProcessFileCallback = function () { return true; };
  61419. this._engine = engine;
  61420. this._currentScene = scene;
  61421. this._sceneLoadedCallback = sceneLoadedCallback;
  61422. this._progressCallback = progressCallback;
  61423. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61424. this._textureLoadingCallback = textureLoadingCallback;
  61425. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61426. this._onReloadCallback = onReloadCallback;
  61427. this._errorCallback = errorCallback;
  61428. }
  61429. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61430. var _this = this;
  61431. if (elementToMonitor) {
  61432. this._elementToMonitor = elementToMonitor;
  61433. this._dragEnterHandler = function (e) { _this.drag(e); };
  61434. this._dragOverHandler = function (e) { _this.drag(e); };
  61435. this._dropHandler = function (e) { _this.drop(e); };
  61436. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61437. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61438. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61439. }
  61440. };
  61441. FilesInput.prototype.dispose = function () {
  61442. if (!this._elementToMonitor) {
  61443. return;
  61444. }
  61445. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61446. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61447. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61448. };
  61449. FilesInput.prototype.renderFunction = function () {
  61450. if (this._additionalRenderLoopLogicCallback) {
  61451. this._additionalRenderLoopLogicCallback();
  61452. }
  61453. if (this._currentScene) {
  61454. if (this._textureLoadingCallback) {
  61455. var remaining = this._currentScene.getWaitingItemsCount();
  61456. if (remaining > 0) {
  61457. this._textureLoadingCallback(remaining);
  61458. }
  61459. }
  61460. this._currentScene.render();
  61461. }
  61462. };
  61463. FilesInput.prototype.drag = function (e) {
  61464. e.stopPropagation();
  61465. e.preventDefault();
  61466. };
  61467. FilesInput.prototype.drop = function (eventDrop) {
  61468. eventDrop.stopPropagation();
  61469. eventDrop.preventDefault();
  61470. this.loadFiles(eventDrop);
  61471. };
  61472. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61473. var _this = this;
  61474. var reader = folder.createReader();
  61475. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61476. reader.readEntries(function (entries) {
  61477. remaining.count += entries.length;
  61478. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61479. var entry = entries_1[_i];
  61480. if (entry.isFile) {
  61481. entry.file(function (file) {
  61482. file.correctName = relativePath + file.name;
  61483. files.push(file);
  61484. if (--remaining.count === 0) {
  61485. callback();
  61486. }
  61487. });
  61488. }
  61489. else if (entry.isDirectory) {
  61490. _this._traverseFolder(entry, files, remaining, callback);
  61491. }
  61492. }
  61493. if (--remaining.count) {
  61494. callback();
  61495. }
  61496. });
  61497. };
  61498. FilesInput.prototype._processFiles = function (files) {
  61499. for (var i = 0; i < files.length; i++) {
  61500. var name = files[i].correctName.toLowerCase();
  61501. var extension = name.split('.').pop();
  61502. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61503. continue;
  61504. }
  61505. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61506. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61507. this._sceneFileToLoad = files[i];
  61508. }
  61509. else {
  61510. FilesInput.FilesToLoad[name] = files[i];
  61511. }
  61512. }
  61513. };
  61514. FilesInput.prototype.loadFiles = function (event) {
  61515. var _this = this;
  61516. if (this._startingProcessingFilesCallback)
  61517. this._startingProcessingFilesCallback();
  61518. // Handling data transfer via drag'n'drop
  61519. if (event && event.dataTransfer && event.dataTransfer.files) {
  61520. this._filesToLoad = event.dataTransfer.files;
  61521. }
  61522. // Handling files from input files
  61523. if (event && event.target && event.target.files) {
  61524. this._filesToLoad = event.target.files;
  61525. }
  61526. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61527. var files_1 = new Array();
  61528. var folders = [];
  61529. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61530. for (var i = 0; i < this._filesToLoad.length; i++) {
  61531. var fileToLoad = this._filesToLoad[i];
  61532. var name_1 = fileToLoad.name.toLowerCase();
  61533. var entry = void 0;
  61534. fileToLoad.correctName = name_1;
  61535. if (items) {
  61536. var item = items[i];
  61537. if (item.getAsEntry) {
  61538. entry = item.getAsEntry();
  61539. }
  61540. else if (item.webkitGetAsEntry) {
  61541. entry = item.webkitGetAsEntry();
  61542. }
  61543. }
  61544. if (!entry) {
  61545. files_1.push(fileToLoad);
  61546. }
  61547. else {
  61548. if (entry.isDirectory) {
  61549. folders.push(entry);
  61550. }
  61551. else {
  61552. files_1.push(fileToLoad);
  61553. }
  61554. }
  61555. }
  61556. if (folders.length === 0) {
  61557. this._processFiles(files_1);
  61558. this._processReload();
  61559. }
  61560. else {
  61561. var remaining = { count: folders.length };
  61562. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61563. var folder = folders_1[_i];
  61564. this._traverseFolder(folder, files_1, remaining, function () {
  61565. _this._processFiles(files_1);
  61566. if (remaining.count === 0) {
  61567. _this._processReload();
  61568. }
  61569. });
  61570. }
  61571. }
  61572. }
  61573. };
  61574. FilesInput.prototype._processReload = function () {
  61575. if (this._onReloadCallback) {
  61576. this._onReloadCallback(this._sceneFileToLoad);
  61577. }
  61578. else {
  61579. this.reload();
  61580. }
  61581. };
  61582. FilesInput.prototype.reload = function () {
  61583. var _this = this;
  61584. // If a scene file has been provided
  61585. if (this._sceneFileToLoad) {
  61586. if (this._currentScene) {
  61587. if (BABYLON.Tools.errorsCount > 0) {
  61588. BABYLON.Tools.ClearLogCache();
  61589. }
  61590. this._engine.stopRenderLoop();
  61591. this._currentScene.dispose();
  61592. }
  61593. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61594. if (_this._progressCallback) {
  61595. _this._progressCallback(progress);
  61596. }
  61597. }).then(function (scene) {
  61598. _this._currentScene = scene;
  61599. if (_this._sceneLoadedCallback) {
  61600. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61601. }
  61602. // Wait for textures and shaders to be ready
  61603. _this._currentScene.executeWhenReady(function () {
  61604. _this._engine.runRenderLoop(function () {
  61605. _this.renderFunction();
  61606. });
  61607. });
  61608. }).catch(function (error) {
  61609. if (_this._errorCallback) {
  61610. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61611. }
  61612. });
  61613. }
  61614. else {
  61615. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61616. }
  61617. };
  61618. FilesInput.FilesToLoad = {};
  61619. return FilesInput;
  61620. }());
  61621. BABYLON.FilesInput = FilesInput;
  61622. })(BABYLON || (BABYLON = {}));
  61623. //# sourceMappingURL=babylon.filesInput.js.map
  61624. var BABYLON;
  61625. (function (BABYLON) {
  61626. /**
  61627. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61628. * The underlying implementation relies on an associative array to ensure the best performances.
  61629. * The value can be anything including 'null' but except 'undefined'
  61630. */
  61631. var StringDictionary = /** @class */ (function () {
  61632. function StringDictionary() {
  61633. this._count = 0;
  61634. this._data = {};
  61635. }
  61636. /**
  61637. * This will clear this dictionary and copy the content from the 'source' one.
  61638. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61639. * @param source the dictionary to take the content from and copy to this dictionary
  61640. */
  61641. StringDictionary.prototype.copyFrom = function (source) {
  61642. var _this = this;
  61643. this.clear();
  61644. source.forEach(function (t, v) { return _this.add(t, v); });
  61645. };
  61646. /**
  61647. * Get a value based from its key
  61648. * @param key the given key to get the matching value from
  61649. * @return the value if found, otherwise undefined is returned
  61650. */
  61651. StringDictionary.prototype.get = function (key) {
  61652. var val = this._data[key];
  61653. if (val !== undefined) {
  61654. return val;
  61655. }
  61656. return undefined;
  61657. };
  61658. /**
  61659. * Get a value from its key or add it if it doesn't exist.
  61660. * This method will ensure you that a given key/data will be present in the dictionary.
  61661. * @param key the given key to get the matching value from
  61662. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61663. * The factory will only be invoked if there's no data for the given key.
  61664. * @return the value corresponding to the key.
  61665. */
  61666. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61667. var val = this.get(key);
  61668. if (val !== undefined) {
  61669. return val;
  61670. }
  61671. val = factory(key);
  61672. if (val) {
  61673. this.add(key, val);
  61674. }
  61675. return val;
  61676. };
  61677. /**
  61678. * Get a value from its key if present in the dictionary otherwise add it
  61679. * @param key the key to get the value from
  61680. * @param val if there's no such key/value pair in the dictionary add it with this value
  61681. * @return the value corresponding to the key
  61682. */
  61683. StringDictionary.prototype.getOrAdd = function (key, val) {
  61684. var curVal = this.get(key);
  61685. if (curVal !== undefined) {
  61686. return curVal;
  61687. }
  61688. this.add(key, val);
  61689. return val;
  61690. };
  61691. /**
  61692. * Check if there's a given key in the dictionary
  61693. * @param key the key to check for
  61694. * @return true if the key is present, false otherwise
  61695. */
  61696. StringDictionary.prototype.contains = function (key) {
  61697. return this._data[key] !== undefined;
  61698. };
  61699. /**
  61700. * Add a new key and its corresponding value
  61701. * @param key the key to add
  61702. * @param value the value corresponding to the key
  61703. * @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
  61704. */
  61705. StringDictionary.prototype.add = function (key, value) {
  61706. if (this._data[key] !== undefined) {
  61707. return false;
  61708. }
  61709. this._data[key] = value;
  61710. ++this._count;
  61711. return true;
  61712. };
  61713. StringDictionary.prototype.set = function (key, value) {
  61714. if (this._data[key] === undefined) {
  61715. return false;
  61716. }
  61717. this._data[key] = value;
  61718. return true;
  61719. };
  61720. /**
  61721. * Get the element of the given key and remove it from the dictionary
  61722. * @param key
  61723. */
  61724. StringDictionary.prototype.getAndRemove = function (key) {
  61725. var val = this.get(key);
  61726. if (val !== undefined) {
  61727. delete this._data[key];
  61728. --this._count;
  61729. return val;
  61730. }
  61731. return null;
  61732. };
  61733. /**
  61734. * Remove a key/value from the dictionary.
  61735. * @param key the key to remove
  61736. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61737. */
  61738. StringDictionary.prototype.remove = function (key) {
  61739. if (this.contains(key)) {
  61740. delete this._data[key];
  61741. --this._count;
  61742. return true;
  61743. }
  61744. return false;
  61745. };
  61746. /**
  61747. * Clear the whole content of the dictionary
  61748. */
  61749. StringDictionary.prototype.clear = function () {
  61750. this._data = {};
  61751. this._count = 0;
  61752. };
  61753. Object.defineProperty(StringDictionary.prototype, "count", {
  61754. get: function () {
  61755. return this._count;
  61756. },
  61757. enumerable: true,
  61758. configurable: true
  61759. });
  61760. /**
  61761. * Execute a callback on each key/val of the dictionary.
  61762. * Note that you can remove any element in this dictionary in the callback implementation
  61763. * @param callback the callback to execute on a given key/value pair
  61764. */
  61765. StringDictionary.prototype.forEach = function (callback) {
  61766. for (var cur in this._data) {
  61767. var val = this._data[cur];
  61768. callback(cur, val);
  61769. }
  61770. };
  61771. /**
  61772. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61773. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61774. * Note that you can remove any element in this dictionary in the callback implementation
  61775. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61776. */
  61777. StringDictionary.prototype.first = function (callback) {
  61778. for (var cur in this._data) {
  61779. var val = this._data[cur];
  61780. var res = callback(cur, val);
  61781. if (res) {
  61782. return res;
  61783. }
  61784. }
  61785. return null;
  61786. };
  61787. return StringDictionary;
  61788. }());
  61789. BABYLON.StringDictionary = StringDictionary;
  61790. })(BABYLON || (BABYLON = {}));
  61791. //# sourceMappingURL=babylon.stringDictionary.js.map
  61792. var BABYLON;
  61793. (function (BABYLON) {
  61794. var Tags = /** @class */ (function () {
  61795. function Tags() {
  61796. }
  61797. Tags.EnableFor = function (obj) {
  61798. obj._tags = obj._tags || {};
  61799. obj.hasTags = function () {
  61800. return Tags.HasTags(obj);
  61801. };
  61802. obj.addTags = function (tagsString) {
  61803. return Tags.AddTagsTo(obj, tagsString);
  61804. };
  61805. obj.removeTags = function (tagsString) {
  61806. return Tags.RemoveTagsFrom(obj, tagsString);
  61807. };
  61808. obj.matchesTagsQuery = function (tagsQuery) {
  61809. return Tags.MatchesQuery(obj, tagsQuery);
  61810. };
  61811. };
  61812. Tags.DisableFor = function (obj) {
  61813. delete obj._tags;
  61814. delete obj.hasTags;
  61815. delete obj.addTags;
  61816. delete obj.removeTags;
  61817. delete obj.matchesTagsQuery;
  61818. };
  61819. Tags.HasTags = function (obj) {
  61820. if (!obj._tags) {
  61821. return false;
  61822. }
  61823. return !BABYLON.Tools.IsEmpty(obj._tags);
  61824. };
  61825. Tags.GetTags = function (obj, asString) {
  61826. if (asString === void 0) { asString = true; }
  61827. if (!obj._tags) {
  61828. return null;
  61829. }
  61830. if (asString) {
  61831. var tagsArray = [];
  61832. for (var tag in obj._tags) {
  61833. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61834. tagsArray.push(tag);
  61835. }
  61836. }
  61837. return tagsArray.join(" ");
  61838. }
  61839. else {
  61840. return obj._tags;
  61841. }
  61842. };
  61843. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61844. // a tag cannot start with '||', '&&', and '!'
  61845. // it cannot contain whitespaces
  61846. Tags.AddTagsTo = function (obj, tagsString) {
  61847. if (!tagsString) {
  61848. return;
  61849. }
  61850. if (typeof tagsString !== "string") {
  61851. return;
  61852. }
  61853. var tags = tagsString.split(" ");
  61854. tags.forEach(function (tag, index, array) {
  61855. Tags._AddTagTo(obj, tag);
  61856. });
  61857. };
  61858. Tags._AddTagTo = function (obj, tag) {
  61859. tag = tag.trim();
  61860. if (tag === "" || tag === "true" || tag === "false") {
  61861. return;
  61862. }
  61863. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61864. return;
  61865. }
  61866. Tags.EnableFor(obj);
  61867. obj._tags[tag] = true;
  61868. };
  61869. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61870. if (!Tags.HasTags(obj)) {
  61871. return;
  61872. }
  61873. var tags = tagsString.split(" ");
  61874. for (var t in tags) {
  61875. Tags._RemoveTagFrom(obj, tags[t]);
  61876. }
  61877. };
  61878. Tags._RemoveTagFrom = function (obj, tag) {
  61879. delete obj._tags[tag];
  61880. };
  61881. Tags.MatchesQuery = function (obj, tagsQuery) {
  61882. if (tagsQuery === undefined) {
  61883. return true;
  61884. }
  61885. if (tagsQuery === "") {
  61886. return Tags.HasTags(obj);
  61887. }
  61888. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61889. };
  61890. return Tags;
  61891. }());
  61892. BABYLON.Tags = Tags;
  61893. })(BABYLON || (BABYLON = {}));
  61894. //# sourceMappingURL=babylon.tags.js.map
  61895. var BABYLON;
  61896. (function (BABYLON) {
  61897. var AndOrNotEvaluator = /** @class */ (function () {
  61898. function AndOrNotEvaluator() {
  61899. }
  61900. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61901. if (!query.match(/\([^\(\)]*\)/g)) {
  61902. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61903. }
  61904. else {
  61905. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61906. // remove parenthesis
  61907. r = r.slice(1, r.length - 1);
  61908. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61909. });
  61910. }
  61911. if (query === "true") {
  61912. return true;
  61913. }
  61914. if (query === "false") {
  61915. return false;
  61916. }
  61917. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61918. };
  61919. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61920. evaluateCallback = evaluateCallback || (function (r) {
  61921. return r === "true" ? true : false;
  61922. });
  61923. var result;
  61924. var or = parenthesisContent.split("||");
  61925. for (var i in or) {
  61926. if (or.hasOwnProperty(i)) {
  61927. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61928. var and = ori.split("&&");
  61929. if (and.length > 1) {
  61930. for (var j = 0; j < and.length; ++j) {
  61931. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61932. if (andj !== "true" && andj !== "false") {
  61933. if (andj[0] === "!") {
  61934. result = !evaluateCallback(andj.substring(1));
  61935. }
  61936. else {
  61937. result = evaluateCallback(andj);
  61938. }
  61939. }
  61940. else {
  61941. result = andj === "true" ? true : false;
  61942. }
  61943. if (!result) {
  61944. ori = "false";
  61945. break;
  61946. }
  61947. }
  61948. }
  61949. if (result || ori === "true") {
  61950. result = true;
  61951. break;
  61952. }
  61953. // result equals false (or undefined)
  61954. if (ori !== "true" && ori !== "false") {
  61955. if (ori[0] === "!") {
  61956. result = !evaluateCallback(ori.substring(1));
  61957. }
  61958. else {
  61959. result = evaluateCallback(ori);
  61960. }
  61961. }
  61962. else {
  61963. result = ori === "true" ? true : false;
  61964. }
  61965. }
  61966. }
  61967. // the whole parenthesis scope is replaced by 'true' or 'false'
  61968. return result ? "true" : "false";
  61969. };
  61970. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61971. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61972. // remove whitespaces
  61973. r = r.replace(/[\s]/g, function () { return ""; });
  61974. return r.length % 2 ? "!" : "";
  61975. });
  61976. booleanString = booleanString.trim();
  61977. if (booleanString === "!true") {
  61978. booleanString = "false";
  61979. }
  61980. else if (booleanString === "!false") {
  61981. booleanString = "true";
  61982. }
  61983. return booleanString;
  61984. };
  61985. return AndOrNotEvaluator;
  61986. }());
  61987. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61988. })(BABYLON || (BABYLON = {}));
  61989. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61990. var BABYLON;
  61991. (function (BABYLON) {
  61992. var Database = /** @class */ (function () {
  61993. function Database(urlToScene, callbackManifestChecked) {
  61994. // Handling various flavors of prefixed version of IndexedDB
  61995. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61996. this.callbackManifestChecked = callbackManifestChecked;
  61997. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61998. this.db = null;
  61999. this._enableSceneOffline = false;
  62000. this._enableTexturesOffline = false;
  62001. this.manifestVersionFound = 0;
  62002. this.mustUpdateRessources = false;
  62003. this.hasReachedQuota = false;
  62004. if (!Database.IDBStorageEnabled) {
  62005. this.callbackManifestChecked(true);
  62006. }
  62007. else {
  62008. this.checkManifestFile();
  62009. }
  62010. }
  62011. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62012. get: function () {
  62013. return this._enableSceneOffline;
  62014. },
  62015. enumerable: true,
  62016. configurable: true
  62017. });
  62018. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62019. get: function () {
  62020. return this._enableTexturesOffline;
  62021. },
  62022. enumerable: true,
  62023. configurable: true
  62024. });
  62025. Database.prototype.checkManifestFile = function () {
  62026. var _this = this;
  62027. var noManifestFile = function () {
  62028. _this._enableSceneOffline = false;
  62029. _this._enableTexturesOffline = false;
  62030. _this.callbackManifestChecked(false);
  62031. };
  62032. var timeStampUsed = false;
  62033. var manifestURL = this.currentSceneUrl + ".manifest";
  62034. var xhr = new XMLHttpRequest();
  62035. if (navigator.onLine) {
  62036. // Adding a timestamp to by-pass browsers' cache
  62037. timeStampUsed = true;
  62038. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62039. }
  62040. xhr.open("GET", manifestURL, true);
  62041. xhr.addEventListener("load", function () {
  62042. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62043. try {
  62044. var manifestFile = JSON.parse(xhr.response);
  62045. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62046. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62047. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62048. _this.manifestVersionFound = manifestFile.version;
  62049. }
  62050. if (_this.callbackManifestChecked) {
  62051. _this.callbackManifestChecked(true);
  62052. }
  62053. }
  62054. catch (ex) {
  62055. noManifestFile();
  62056. }
  62057. }
  62058. else {
  62059. noManifestFile();
  62060. }
  62061. }, false);
  62062. xhr.addEventListener("error", function (event) {
  62063. if (timeStampUsed) {
  62064. timeStampUsed = false;
  62065. // Let's retry without the timeStamp
  62066. // It could fail when coupled with HTML5 Offline API
  62067. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62068. xhr.open("GET", retryManifestURL, true);
  62069. xhr.send();
  62070. }
  62071. else {
  62072. noManifestFile();
  62073. }
  62074. }, false);
  62075. try {
  62076. xhr.send();
  62077. }
  62078. catch (ex) {
  62079. BABYLON.Tools.Error("Error on XHR send request.");
  62080. this.callbackManifestChecked(false);
  62081. }
  62082. };
  62083. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62084. var _this = this;
  62085. var handleError = function () {
  62086. _this.isSupported = false;
  62087. if (errorCallback)
  62088. errorCallback();
  62089. };
  62090. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62091. // Your browser doesn't support IndexedDB
  62092. this.isSupported = false;
  62093. if (errorCallback)
  62094. errorCallback();
  62095. }
  62096. else {
  62097. // If the DB hasn't been opened or created yet
  62098. if (!this.db) {
  62099. this.hasReachedQuota = false;
  62100. this.isSupported = true;
  62101. var request = this.idbFactory.open("babylonjs", 1);
  62102. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62103. request.onerror = function (event) {
  62104. handleError();
  62105. };
  62106. // executes when a version change transaction cannot complete due to other active transactions
  62107. request.onblocked = function (event) {
  62108. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62109. handleError();
  62110. };
  62111. // DB has been opened successfully
  62112. request.onsuccess = function (event) {
  62113. _this.db = request.result;
  62114. successCallback();
  62115. };
  62116. // Initialization of the DB. Creating Scenes & Textures stores
  62117. request.onupgradeneeded = function (event) {
  62118. _this.db = (event.target).result;
  62119. if (_this.db) {
  62120. try {
  62121. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62122. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62123. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62124. }
  62125. catch (ex) {
  62126. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62127. handleError();
  62128. }
  62129. }
  62130. };
  62131. }
  62132. else {
  62133. if (successCallback)
  62134. successCallback();
  62135. }
  62136. }
  62137. };
  62138. Database.prototype.loadImageFromDB = function (url, image) {
  62139. var _this = this;
  62140. var completeURL = Database.ReturnFullUrlLocation(url);
  62141. var saveAndLoadImage = function () {
  62142. if (!_this.hasReachedQuota && _this.db !== null) {
  62143. // the texture is not yet in the DB, let's try to save it
  62144. _this._saveImageIntoDBAsync(completeURL, image);
  62145. }
  62146. else {
  62147. image.src = url;
  62148. }
  62149. };
  62150. if (!this.mustUpdateRessources) {
  62151. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62152. }
  62153. else {
  62154. saveAndLoadImage();
  62155. }
  62156. };
  62157. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62158. if (this.isSupported && this.db !== null) {
  62159. var texture;
  62160. var transaction = this.db.transaction(["textures"]);
  62161. transaction.onabort = function (event) {
  62162. image.src = url;
  62163. };
  62164. transaction.oncomplete = function (event) {
  62165. var blobTextureURL;
  62166. if (texture) {
  62167. var URL = window.URL || window.webkitURL;
  62168. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62169. image.onerror = function () {
  62170. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62171. image.src = url;
  62172. };
  62173. image.src = blobTextureURL;
  62174. }
  62175. else {
  62176. notInDBCallback();
  62177. }
  62178. };
  62179. var getRequest = transaction.objectStore("textures").get(url);
  62180. getRequest.onsuccess = function (event) {
  62181. texture = (event.target).result;
  62182. };
  62183. getRequest.onerror = function (event) {
  62184. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62185. image.src = url;
  62186. };
  62187. }
  62188. else {
  62189. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62190. image.src = url;
  62191. }
  62192. };
  62193. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62194. var _this = this;
  62195. if (this.isSupported) {
  62196. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62197. var generateBlobUrl = function () {
  62198. var blobTextureURL;
  62199. if (blob) {
  62200. var URL = window.URL || window.webkitURL;
  62201. try {
  62202. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62203. }
  62204. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62205. catch (ex) {
  62206. blobTextureURL = URL.createObjectURL(blob);
  62207. }
  62208. }
  62209. if (blobTextureURL) {
  62210. image.src = blobTextureURL;
  62211. }
  62212. };
  62213. if (Database.IsUASupportingBlobStorage) {
  62214. var xhr = new XMLHttpRequest(), blob;
  62215. xhr.open("GET", url, true);
  62216. xhr.responseType = "blob";
  62217. xhr.addEventListener("load", function () {
  62218. if (xhr.status === 200 && _this.db) {
  62219. // Blob as response (XHR2)
  62220. blob = xhr.response;
  62221. var transaction = _this.db.transaction(["textures"], "readwrite");
  62222. // the transaction could abort because of a QuotaExceededError error
  62223. transaction.onabort = function (event) {
  62224. try {
  62225. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62226. var srcElement = (event.srcElement || event.target);
  62227. var error = srcElement.error;
  62228. if (error && error.name === "QuotaExceededError") {
  62229. _this.hasReachedQuota = true;
  62230. }
  62231. }
  62232. catch (ex) { }
  62233. generateBlobUrl();
  62234. };
  62235. transaction.oncomplete = function (event) {
  62236. generateBlobUrl();
  62237. };
  62238. var newTexture = { textureUrl: url, data: blob };
  62239. try {
  62240. // Put the blob into the dabase
  62241. var addRequest = transaction.objectStore("textures").put(newTexture);
  62242. addRequest.onsuccess = function (event) {
  62243. };
  62244. addRequest.onerror = function (event) {
  62245. generateBlobUrl();
  62246. };
  62247. }
  62248. catch (ex) {
  62249. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62250. if (ex.code === 25) {
  62251. Database.IsUASupportingBlobStorage = false;
  62252. }
  62253. image.src = url;
  62254. }
  62255. }
  62256. else {
  62257. image.src = url;
  62258. }
  62259. }, false);
  62260. xhr.addEventListener("error", function (event) {
  62261. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62262. image.src = url;
  62263. }, false);
  62264. xhr.send();
  62265. }
  62266. else {
  62267. image.src = url;
  62268. }
  62269. }
  62270. else {
  62271. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62272. image.src = url;
  62273. }
  62274. };
  62275. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62276. var _this = this;
  62277. var updateVersion = function () {
  62278. // the version is not yet in the DB or we need to update it
  62279. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62280. };
  62281. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62282. };
  62283. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62284. var _this = this;
  62285. if (this.isSupported && this.db) {
  62286. var version;
  62287. try {
  62288. var transaction = this.db.transaction(["versions"]);
  62289. transaction.oncomplete = function (event) {
  62290. if (version) {
  62291. // If the version in the JSON file is > than the version in DB
  62292. if (_this.manifestVersionFound > version.data) {
  62293. _this.mustUpdateRessources = true;
  62294. updateInDBCallback();
  62295. }
  62296. else {
  62297. callback(version.data);
  62298. }
  62299. }
  62300. else {
  62301. _this.mustUpdateRessources = true;
  62302. updateInDBCallback();
  62303. }
  62304. };
  62305. transaction.onabort = function (event) {
  62306. callback(-1);
  62307. };
  62308. var getRequest = transaction.objectStore("versions").get(url);
  62309. getRequest.onsuccess = function (event) {
  62310. version = (event.target).result;
  62311. };
  62312. getRequest.onerror = function (event) {
  62313. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62314. callback(-1);
  62315. };
  62316. }
  62317. catch (ex) {
  62318. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62319. callback(-1);
  62320. }
  62321. }
  62322. else {
  62323. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62324. callback(-1);
  62325. }
  62326. };
  62327. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62328. var _this = this;
  62329. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62330. try {
  62331. // Open a transaction to the database
  62332. var transaction = this.db.transaction(["versions"], "readwrite");
  62333. // the transaction could abort because of a QuotaExceededError error
  62334. transaction.onabort = function (event) {
  62335. try {
  62336. var error = event.srcElement['error'];
  62337. if (error && error.name === "QuotaExceededError") {
  62338. _this.hasReachedQuota = true;
  62339. }
  62340. }
  62341. catch (ex) { }
  62342. callback(-1);
  62343. };
  62344. transaction.oncomplete = function (event) {
  62345. callback(_this.manifestVersionFound);
  62346. };
  62347. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62348. // Put the scene into the database
  62349. var addRequest = transaction.objectStore("versions").put(newVersion);
  62350. addRequest.onsuccess = function (event) {
  62351. };
  62352. addRequest.onerror = function (event) {
  62353. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62354. };
  62355. }
  62356. catch (ex) {
  62357. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62358. callback(-1);
  62359. }
  62360. }
  62361. else {
  62362. callback(-1);
  62363. }
  62364. };
  62365. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62366. var _this = this;
  62367. var completeUrl = Database.ReturnFullUrlLocation(url);
  62368. var saveAndLoadFile = function () {
  62369. // the scene is not yet in the DB, let's try to save it
  62370. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62371. };
  62372. this._checkVersionFromDB(completeUrl, function (version) {
  62373. if (version !== -1) {
  62374. if (!_this.mustUpdateRessources) {
  62375. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62376. }
  62377. else {
  62378. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62379. }
  62380. }
  62381. else {
  62382. if (errorCallback) {
  62383. errorCallback();
  62384. }
  62385. }
  62386. });
  62387. };
  62388. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62389. if (this.isSupported && this.db) {
  62390. var targetStore;
  62391. if (url.indexOf(".babylon") !== -1) {
  62392. targetStore = "scenes";
  62393. }
  62394. else {
  62395. targetStore = "textures";
  62396. }
  62397. var file;
  62398. var transaction = this.db.transaction([targetStore]);
  62399. transaction.oncomplete = function (event) {
  62400. if (file) {
  62401. callback(file.data);
  62402. }
  62403. else {
  62404. notInDBCallback();
  62405. }
  62406. };
  62407. transaction.onabort = function (event) {
  62408. notInDBCallback();
  62409. };
  62410. var getRequest = transaction.objectStore(targetStore).get(url);
  62411. getRequest.onsuccess = function (event) {
  62412. file = (event.target).result;
  62413. };
  62414. getRequest.onerror = function (event) {
  62415. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62416. notInDBCallback();
  62417. };
  62418. }
  62419. else {
  62420. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62421. callback();
  62422. }
  62423. };
  62424. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62425. var _this = this;
  62426. if (this.isSupported) {
  62427. var targetStore;
  62428. if (url.indexOf(".babylon") !== -1) {
  62429. targetStore = "scenes";
  62430. }
  62431. else {
  62432. targetStore = "textures";
  62433. }
  62434. // Create XHR
  62435. var xhr = new XMLHttpRequest();
  62436. var fileData;
  62437. xhr.open("GET", url, true);
  62438. if (useArrayBuffer) {
  62439. xhr.responseType = "arraybuffer";
  62440. }
  62441. if (progressCallback) {
  62442. xhr.onprogress = progressCallback;
  62443. }
  62444. xhr.addEventListener("load", function () {
  62445. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62446. // Blob as response (XHR2)
  62447. //fileData = xhr.responseText;
  62448. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62449. if (!_this.hasReachedQuota && _this.db) {
  62450. // Open a transaction to the database
  62451. var transaction = _this.db.transaction([targetStore], "readwrite");
  62452. // the transaction could abort because of a QuotaExceededError error
  62453. transaction.onabort = function (event) {
  62454. try {
  62455. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62456. var error = event.srcElement['error'];
  62457. if (error && error.name === "QuotaExceededError") {
  62458. _this.hasReachedQuota = true;
  62459. }
  62460. }
  62461. catch (ex) { }
  62462. callback(fileData);
  62463. };
  62464. transaction.oncomplete = function (event) {
  62465. callback(fileData);
  62466. };
  62467. var newFile;
  62468. if (targetStore === "scenes") {
  62469. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62470. }
  62471. else {
  62472. newFile = { textureUrl: url, data: fileData };
  62473. }
  62474. try {
  62475. // Put the scene into the database
  62476. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62477. addRequest.onsuccess = function (event) {
  62478. };
  62479. addRequest.onerror = function (event) {
  62480. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62481. };
  62482. }
  62483. catch (ex) {
  62484. callback(fileData);
  62485. }
  62486. }
  62487. else {
  62488. callback(fileData);
  62489. }
  62490. }
  62491. else {
  62492. callback();
  62493. }
  62494. }, false);
  62495. xhr.addEventListener("error", function (event) {
  62496. BABYLON.Tools.Error("error on XHR request.");
  62497. callback();
  62498. }, false);
  62499. xhr.send();
  62500. }
  62501. else {
  62502. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62503. callback();
  62504. }
  62505. };
  62506. Database.IsUASupportingBlobStorage = true;
  62507. Database.IDBStorageEnabled = true;
  62508. Database.parseURL = function (url) {
  62509. var a = document.createElement('a');
  62510. a.href = url;
  62511. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62512. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62513. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62514. return absLocation;
  62515. };
  62516. Database.ReturnFullUrlLocation = function (url) {
  62517. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62518. return (Database.parseURL(window.location.href) + url);
  62519. }
  62520. else {
  62521. return url;
  62522. }
  62523. };
  62524. return Database;
  62525. }());
  62526. BABYLON.Database = Database;
  62527. })(BABYLON || (BABYLON = {}));
  62528. //# sourceMappingURL=babylon.database.js.map
  62529. var BABYLON;
  62530. (function (BABYLON) {
  62531. var FresnelParameters = /** @class */ (function () {
  62532. function FresnelParameters() {
  62533. this._isEnabled = true;
  62534. this.leftColor = BABYLON.Color3.White();
  62535. this.rightColor = BABYLON.Color3.Black();
  62536. this.bias = 0;
  62537. this.power = 1;
  62538. }
  62539. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62540. get: function () {
  62541. return this._isEnabled;
  62542. },
  62543. set: function (value) {
  62544. if (this._isEnabled === value) {
  62545. return;
  62546. }
  62547. this._isEnabled = value;
  62548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62549. },
  62550. enumerable: true,
  62551. configurable: true
  62552. });
  62553. FresnelParameters.prototype.clone = function () {
  62554. var newFresnelParameters = new FresnelParameters();
  62555. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62556. return newFresnelParameters;
  62557. };
  62558. FresnelParameters.prototype.serialize = function () {
  62559. var serializationObject = {};
  62560. serializationObject.isEnabled = this.isEnabled;
  62561. serializationObject.leftColor = this.leftColor;
  62562. serializationObject.rightColor = this.rightColor;
  62563. serializationObject.bias = this.bias;
  62564. serializationObject.power = this.power;
  62565. return serializationObject;
  62566. };
  62567. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62568. var fresnelParameters = new FresnelParameters();
  62569. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62570. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62571. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62572. fresnelParameters.bias = parsedFresnelParameters.bias;
  62573. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62574. return fresnelParameters;
  62575. };
  62576. return FresnelParameters;
  62577. }());
  62578. BABYLON.FresnelParameters = FresnelParameters;
  62579. })(BABYLON || (BABYLON = {}));
  62580. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62581. var BABYLON;
  62582. (function (BABYLON) {
  62583. var MultiMaterial = /** @class */ (function (_super) {
  62584. __extends(MultiMaterial, _super);
  62585. function MultiMaterial(name, scene) {
  62586. var _this = _super.call(this, name, scene, true) || this;
  62587. scene.multiMaterials.push(_this);
  62588. _this.subMaterials = new Array();
  62589. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62590. return _this;
  62591. }
  62592. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62593. get: function () {
  62594. return this._subMaterials;
  62595. },
  62596. set: function (value) {
  62597. this._subMaterials = value;
  62598. this._hookArray(value);
  62599. },
  62600. enumerable: true,
  62601. configurable: true
  62602. });
  62603. MultiMaterial.prototype._hookArray = function (array) {
  62604. var _this = this;
  62605. var oldPush = array.push;
  62606. array.push = function () {
  62607. var items = [];
  62608. for (var _i = 0; _i < arguments.length; _i++) {
  62609. items[_i] = arguments[_i];
  62610. }
  62611. var result = oldPush.apply(array, items);
  62612. _this._markAllSubMeshesAsTexturesDirty();
  62613. return result;
  62614. };
  62615. var oldSplice = array.splice;
  62616. array.splice = function (index, deleteCount) {
  62617. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62618. _this._markAllSubMeshesAsTexturesDirty();
  62619. return deleted;
  62620. };
  62621. };
  62622. // Properties
  62623. MultiMaterial.prototype.getSubMaterial = function (index) {
  62624. if (index < 0 || index >= this.subMaterials.length) {
  62625. return this.getScene().defaultMaterial;
  62626. }
  62627. return this.subMaterials[index];
  62628. };
  62629. MultiMaterial.prototype.getActiveTextures = function () {
  62630. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62631. if (subMaterial) {
  62632. return subMaterial.getActiveTextures();
  62633. }
  62634. else {
  62635. return [];
  62636. }
  62637. }));
  62638. var _a;
  62639. };
  62640. // Methods
  62641. MultiMaterial.prototype.getClassName = function () {
  62642. return "MultiMaterial";
  62643. };
  62644. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62645. for (var index = 0; index < this.subMaterials.length; index++) {
  62646. var subMaterial = this.subMaterials[index];
  62647. if (subMaterial) {
  62648. if (subMaterial.storeEffectOnSubMeshes) {
  62649. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62650. return false;
  62651. }
  62652. continue;
  62653. }
  62654. if (!subMaterial.isReady(mesh)) {
  62655. return false;
  62656. }
  62657. }
  62658. }
  62659. return true;
  62660. };
  62661. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62662. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62663. for (var index = 0; index < this.subMaterials.length; index++) {
  62664. var subMaterial = null;
  62665. var current = this.subMaterials[index];
  62666. if (cloneChildren && current) {
  62667. subMaterial = current.clone(name + "-" + current.name);
  62668. }
  62669. else {
  62670. subMaterial = this.subMaterials[index];
  62671. }
  62672. newMultiMaterial.subMaterials.push(subMaterial);
  62673. }
  62674. return newMultiMaterial;
  62675. };
  62676. MultiMaterial.prototype.serialize = function () {
  62677. var serializationObject = {};
  62678. serializationObject.name = this.name;
  62679. serializationObject.id = this.id;
  62680. if (BABYLON.Tags) {
  62681. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62682. }
  62683. serializationObject.materials = [];
  62684. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62685. var subMat = this.subMaterials[matIndex];
  62686. if (subMat) {
  62687. serializationObject.materials.push(subMat.id);
  62688. }
  62689. else {
  62690. serializationObject.materials.push(null);
  62691. }
  62692. }
  62693. return serializationObject;
  62694. };
  62695. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62696. var scene = this.getScene();
  62697. if (!scene) {
  62698. return;
  62699. }
  62700. var index = scene.multiMaterials.indexOf(this);
  62701. if (index >= 0) {
  62702. scene.multiMaterials.splice(index, 1);
  62703. }
  62704. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62705. };
  62706. return MultiMaterial;
  62707. }(BABYLON.Material));
  62708. BABYLON.MultiMaterial = MultiMaterial;
  62709. })(BABYLON || (BABYLON = {}));
  62710. //# sourceMappingURL=babylon.multiMaterial.js.map
  62711. var BABYLON;
  62712. (function (BABYLON) {
  62713. var FreeCameraTouchInput = /** @class */ (function () {
  62714. function FreeCameraTouchInput() {
  62715. this._offsetX = null;
  62716. this._offsetY = null;
  62717. this._pointerPressed = new Array();
  62718. this.touchAngularSensibility = 200000.0;
  62719. this.touchMoveSensibility = 250.0;
  62720. }
  62721. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62722. var _this = this;
  62723. var previousPosition = null;
  62724. if (this._pointerInput === undefined) {
  62725. this._onLostFocus = function (evt) {
  62726. _this._offsetX = null;
  62727. _this._offsetY = null;
  62728. };
  62729. this._pointerInput = function (p, s) {
  62730. var evt = p.event;
  62731. if (evt.pointerType === "mouse") {
  62732. return;
  62733. }
  62734. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62735. if (!noPreventDefault) {
  62736. evt.preventDefault();
  62737. }
  62738. _this._pointerPressed.push(evt.pointerId);
  62739. if (_this._pointerPressed.length !== 1) {
  62740. return;
  62741. }
  62742. previousPosition = {
  62743. x: evt.clientX,
  62744. y: evt.clientY
  62745. };
  62746. }
  62747. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62748. if (!noPreventDefault) {
  62749. evt.preventDefault();
  62750. }
  62751. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62752. if (index === -1) {
  62753. return;
  62754. }
  62755. _this._pointerPressed.splice(index, 1);
  62756. if (index != 0) {
  62757. return;
  62758. }
  62759. previousPosition = null;
  62760. _this._offsetX = null;
  62761. _this._offsetY = null;
  62762. }
  62763. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62764. if (!noPreventDefault) {
  62765. evt.preventDefault();
  62766. }
  62767. if (!previousPosition) {
  62768. return;
  62769. }
  62770. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62771. if (index != 0) {
  62772. return;
  62773. }
  62774. _this._offsetX = evt.clientX - previousPosition.x;
  62775. _this._offsetY = -(evt.clientY - previousPosition.y);
  62776. }
  62777. };
  62778. }
  62779. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62780. if (this._onLostFocus) {
  62781. element.addEventListener("blur", this._onLostFocus);
  62782. }
  62783. };
  62784. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62785. if (this._pointerInput && element) {
  62786. if (this._observer) {
  62787. this.camera.getScene().onPointerObservable.remove(this._observer);
  62788. this._observer = null;
  62789. }
  62790. if (this._onLostFocus) {
  62791. element.removeEventListener("blur", this._onLostFocus);
  62792. this._onLostFocus = null;
  62793. }
  62794. this._pointerPressed = [];
  62795. this._offsetX = null;
  62796. this._offsetY = null;
  62797. }
  62798. };
  62799. FreeCameraTouchInput.prototype.checkInputs = function () {
  62800. if (this._offsetX && this._offsetY) {
  62801. var camera = this.camera;
  62802. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62803. if (this._pointerPressed.length > 1) {
  62804. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62805. }
  62806. else {
  62807. var speed = camera._computeLocalCameraSpeed();
  62808. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62809. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62810. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62811. }
  62812. }
  62813. };
  62814. FreeCameraTouchInput.prototype.getClassName = function () {
  62815. return "FreeCameraTouchInput";
  62816. };
  62817. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62818. return "touch";
  62819. };
  62820. __decorate([
  62821. BABYLON.serialize()
  62822. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62823. __decorate([
  62824. BABYLON.serialize()
  62825. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62826. return FreeCameraTouchInput;
  62827. }());
  62828. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62829. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62830. })(BABYLON || (BABYLON = {}));
  62831. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62832. var BABYLON;
  62833. (function (BABYLON) {
  62834. // We're mainly based on the logic defined into the FreeCamera code
  62835. var TouchCamera = /** @class */ (function (_super) {
  62836. __extends(TouchCamera, _super);
  62837. //-- end properties for backward compatibility for inputs
  62838. function TouchCamera(name, position, scene) {
  62839. var _this = _super.call(this, name, position, scene) || this;
  62840. _this.inputs.addTouch();
  62841. _this._setupInputs();
  62842. return _this;
  62843. }
  62844. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62845. //-- Begin properties for backward compatibility for inputs
  62846. get: function () {
  62847. var touch = this.inputs.attached["touch"];
  62848. if (touch)
  62849. return touch.touchAngularSensibility;
  62850. return 0;
  62851. },
  62852. set: function (value) {
  62853. var touch = this.inputs.attached["touch"];
  62854. if (touch)
  62855. touch.touchAngularSensibility = value;
  62856. },
  62857. enumerable: true,
  62858. configurable: true
  62859. });
  62860. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62861. get: function () {
  62862. var touch = this.inputs.attached["touch"];
  62863. if (touch)
  62864. return touch.touchMoveSensibility;
  62865. return 0;
  62866. },
  62867. set: function (value) {
  62868. var touch = this.inputs.attached["touch"];
  62869. if (touch)
  62870. touch.touchMoveSensibility = value;
  62871. },
  62872. enumerable: true,
  62873. configurable: true
  62874. });
  62875. TouchCamera.prototype.getClassName = function () {
  62876. return "TouchCamera";
  62877. };
  62878. TouchCamera.prototype._setupInputs = function () {
  62879. var mouse = this.inputs.attached["mouse"];
  62880. if (mouse) {
  62881. mouse.touchEnabled = false;
  62882. }
  62883. };
  62884. return TouchCamera;
  62885. }(BABYLON.FreeCamera));
  62886. BABYLON.TouchCamera = TouchCamera;
  62887. })(BABYLON || (BABYLON = {}));
  62888. //# sourceMappingURL=babylon.touchCamera.js.map
  62889. var BABYLON;
  62890. (function (BABYLON) {
  62891. var ProceduralTexture = /** @class */ (function (_super) {
  62892. __extends(ProceduralTexture, _super);
  62893. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62894. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62895. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62896. if (isCube === void 0) { isCube = false; }
  62897. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62898. _this.isCube = isCube;
  62899. _this.isEnabled = true;
  62900. _this._currentRefreshId = -1;
  62901. _this._refreshRate = 1;
  62902. _this._vertexBuffers = {};
  62903. _this._uniforms = new Array();
  62904. _this._samplers = new Array();
  62905. _this._textures = {};
  62906. _this._floats = {};
  62907. _this._floatsArrays = {};
  62908. _this._colors3 = {};
  62909. _this._colors4 = {};
  62910. _this._vectors2 = {};
  62911. _this._vectors3 = {};
  62912. _this._matrices = {};
  62913. _this._fallbackTextureUsed = false;
  62914. scene._proceduralTextures.push(_this);
  62915. _this._engine = scene.getEngine();
  62916. _this.name = name;
  62917. _this.isRenderTarget = true;
  62918. _this._size = size;
  62919. _this._generateMipMaps = generateMipMaps;
  62920. _this.setFragment(fragment);
  62921. _this._fallbackTexture = fallbackTexture;
  62922. if (isCube) {
  62923. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62924. _this.setFloat("face", 0);
  62925. }
  62926. else {
  62927. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62928. }
  62929. // VBO
  62930. var vertices = [];
  62931. vertices.push(1, 1);
  62932. vertices.push(-1, 1);
  62933. vertices.push(-1, -1);
  62934. vertices.push(1, -1);
  62935. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62936. _this._createIndexBuffer();
  62937. return _this;
  62938. }
  62939. ProceduralTexture.prototype._createIndexBuffer = function () {
  62940. var engine = this._engine;
  62941. // Indices
  62942. var indices = [];
  62943. indices.push(0);
  62944. indices.push(1);
  62945. indices.push(2);
  62946. indices.push(0);
  62947. indices.push(2);
  62948. indices.push(3);
  62949. this._indexBuffer = engine.createIndexBuffer(indices);
  62950. };
  62951. ProceduralTexture.prototype._rebuild = function () {
  62952. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62953. if (vb) {
  62954. vb._rebuild();
  62955. }
  62956. this._createIndexBuffer();
  62957. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62958. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62959. }
  62960. };
  62961. ProceduralTexture.prototype.reset = function () {
  62962. if (this._effect === undefined) {
  62963. return;
  62964. }
  62965. var engine = this._engine;
  62966. engine._releaseEffect(this._effect);
  62967. };
  62968. ProceduralTexture.prototype.isReady = function () {
  62969. var _this = this;
  62970. var engine = this._engine;
  62971. var shaders;
  62972. if (!this._fragment) {
  62973. return false;
  62974. }
  62975. if (this._fallbackTextureUsed) {
  62976. return true;
  62977. }
  62978. if (this._fragment.fragmentElement !== undefined) {
  62979. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62980. }
  62981. else {
  62982. shaders = { vertex: "procedural", fragment: this._fragment };
  62983. }
  62984. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62985. _this.releaseInternalTexture();
  62986. if (_this._fallbackTexture) {
  62987. _this._texture = _this._fallbackTexture._texture;
  62988. if (_this._texture) {
  62989. _this._texture.incrementReferences();
  62990. }
  62991. }
  62992. _this._fallbackTextureUsed = true;
  62993. });
  62994. return this._effect.isReady();
  62995. };
  62996. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62997. this._currentRefreshId = -1;
  62998. };
  62999. ProceduralTexture.prototype.setFragment = function (fragment) {
  63000. this._fragment = fragment;
  63001. };
  63002. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63003. get: function () {
  63004. return this._refreshRate;
  63005. },
  63006. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63007. set: function (value) {
  63008. this._refreshRate = value;
  63009. this.resetRefreshCounter();
  63010. },
  63011. enumerable: true,
  63012. configurable: true
  63013. });
  63014. ProceduralTexture.prototype._shouldRender = function () {
  63015. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63016. return false;
  63017. }
  63018. if (this._fallbackTextureUsed) {
  63019. return false;
  63020. }
  63021. if (this._currentRefreshId === -1) {
  63022. this._currentRefreshId = 1;
  63023. return true;
  63024. }
  63025. if (this.refreshRate === this._currentRefreshId) {
  63026. this._currentRefreshId = 1;
  63027. return true;
  63028. }
  63029. this._currentRefreshId++;
  63030. return false;
  63031. };
  63032. ProceduralTexture.prototype.getRenderSize = function () {
  63033. return this._size;
  63034. };
  63035. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63036. if (this._fallbackTextureUsed) {
  63037. return;
  63038. }
  63039. this.releaseInternalTexture();
  63040. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63041. };
  63042. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63043. if (this._uniforms.indexOf(uniformName) === -1) {
  63044. this._uniforms.push(uniformName);
  63045. }
  63046. };
  63047. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63048. if (this._samplers.indexOf(name) === -1) {
  63049. this._samplers.push(name);
  63050. }
  63051. this._textures[name] = texture;
  63052. return this;
  63053. };
  63054. ProceduralTexture.prototype.setFloat = function (name, value) {
  63055. this._checkUniform(name);
  63056. this._floats[name] = value;
  63057. return this;
  63058. };
  63059. ProceduralTexture.prototype.setFloats = function (name, value) {
  63060. this._checkUniform(name);
  63061. this._floatsArrays[name] = value;
  63062. return this;
  63063. };
  63064. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63065. this._checkUniform(name);
  63066. this._colors3[name] = value;
  63067. return this;
  63068. };
  63069. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63070. this._checkUniform(name);
  63071. this._colors4[name] = value;
  63072. return this;
  63073. };
  63074. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63075. this._checkUniform(name);
  63076. this._vectors2[name] = value;
  63077. return this;
  63078. };
  63079. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63080. this._checkUniform(name);
  63081. this._vectors3[name] = value;
  63082. return this;
  63083. };
  63084. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63085. this._checkUniform(name);
  63086. this._matrices[name] = value;
  63087. return this;
  63088. };
  63089. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63090. var scene = this.getScene();
  63091. if (!scene) {
  63092. return;
  63093. }
  63094. var engine = this._engine;
  63095. // Render
  63096. engine.enableEffect(this._effect);
  63097. engine.setState(false);
  63098. // Texture
  63099. for (var name in this._textures) {
  63100. this._effect.setTexture(name, this._textures[name]);
  63101. }
  63102. // Float
  63103. for (name in this._floats) {
  63104. this._effect.setFloat(name, this._floats[name]);
  63105. }
  63106. // Floats
  63107. for (name in this._floatsArrays) {
  63108. this._effect.setArray(name, this._floatsArrays[name]);
  63109. }
  63110. // Color3
  63111. for (name in this._colors3) {
  63112. this._effect.setColor3(name, this._colors3[name]);
  63113. }
  63114. // Color4
  63115. for (name in this._colors4) {
  63116. var color = this._colors4[name];
  63117. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63118. }
  63119. // Vector2
  63120. for (name in this._vectors2) {
  63121. this._effect.setVector2(name, this._vectors2[name]);
  63122. }
  63123. // Vector3
  63124. for (name in this._vectors3) {
  63125. this._effect.setVector3(name, this._vectors3[name]);
  63126. }
  63127. // Matrix
  63128. for (name in this._matrices) {
  63129. this._effect.setMatrix(name, this._matrices[name]);
  63130. }
  63131. if (!this._texture) {
  63132. return;
  63133. }
  63134. if (this.isCube) {
  63135. for (var face = 0; face < 6; face++) {
  63136. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63137. // VBOs
  63138. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63139. this._effect.setFloat("face", face);
  63140. // Clear
  63141. engine.clear(scene.clearColor, true, true, true);
  63142. // Draw order
  63143. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63144. // Mipmaps
  63145. if (face === 5) {
  63146. engine.generateMipMapsForCubemap(this._texture);
  63147. }
  63148. }
  63149. }
  63150. else {
  63151. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63152. // VBOs
  63153. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63154. // Clear
  63155. engine.clear(scene.clearColor, true, true, true);
  63156. // Draw order
  63157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63158. }
  63159. // Unbind
  63160. engine.unBindFramebuffer(this._texture, this.isCube);
  63161. if (this.onGenerated) {
  63162. this.onGenerated();
  63163. }
  63164. };
  63165. ProceduralTexture.prototype.clone = function () {
  63166. var textureSize = this.getSize();
  63167. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63168. // Base texture
  63169. newTexture.hasAlpha = this.hasAlpha;
  63170. newTexture.level = this.level;
  63171. // RenderTarget Texture
  63172. newTexture.coordinatesMode = this.coordinatesMode;
  63173. return newTexture;
  63174. };
  63175. ProceduralTexture.prototype.dispose = function () {
  63176. var scene = this.getScene();
  63177. if (!scene) {
  63178. return;
  63179. }
  63180. var index = scene._proceduralTextures.indexOf(this);
  63181. if (index >= 0) {
  63182. scene._proceduralTextures.splice(index, 1);
  63183. }
  63184. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63185. if (vertexBuffer) {
  63186. vertexBuffer.dispose();
  63187. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63188. }
  63189. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63190. this._indexBuffer = null;
  63191. }
  63192. _super.prototype.dispose.call(this);
  63193. };
  63194. return ProceduralTexture;
  63195. }(BABYLON.Texture));
  63196. BABYLON.ProceduralTexture = ProceduralTexture;
  63197. })(BABYLON || (BABYLON = {}));
  63198. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63199. var BABYLON;
  63200. (function (BABYLON) {
  63201. var CustomProceduralTexture = /** @class */ (function (_super) {
  63202. __extends(CustomProceduralTexture, _super);
  63203. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63204. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63205. _this._animate = true;
  63206. _this._time = 0;
  63207. _this._texturePath = texturePath;
  63208. //Try to load json
  63209. _this.loadJson(texturePath);
  63210. _this.refreshRate = 1;
  63211. return _this;
  63212. }
  63213. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63214. var _this = this;
  63215. var noConfigFile = function () {
  63216. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63217. try {
  63218. _this.setFragment(_this._texturePath);
  63219. }
  63220. catch (ex) {
  63221. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63222. }
  63223. };
  63224. var configFileUrl = jsonUrl + "/config.json";
  63225. var xhr = new XMLHttpRequest();
  63226. xhr.open("GET", configFileUrl, true);
  63227. xhr.addEventListener("load", function () {
  63228. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63229. try {
  63230. _this._config = JSON.parse(xhr.response);
  63231. _this.updateShaderUniforms();
  63232. _this.updateTextures();
  63233. _this.setFragment(_this._texturePath + "/custom");
  63234. _this._animate = _this._config.animate;
  63235. _this.refreshRate = _this._config.refreshrate;
  63236. }
  63237. catch (ex) {
  63238. noConfigFile();
  63239. }
  63240. }
  63241. else {
  63242. noConfigFile();
  63243. }
  63244. }, false);
  63245. xhr.addEventListener("error", function () {
  63246. noConfigFile();
  63247. }, false);
  63248. try {
  63249. xhr.send();
  63250. }
  63251. catch (ex) {
  63252. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63253. }
  63254. };
  63255. CustomProceduralTexture.prototype.isReady = function () {
  63256. if (!_super.prototype.isReady.call(this)) {
  63257. return false;
  63258. }
  63259. for (var name in this._textures) {
  63260. var texture = this._textures[name];
  63261. if (!texture.isReady()) {
  63262. return false;
  63263. }
  63264. }
  63265. return true;
  63266. };
  63267. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63268. var scene = this.getScene();
  63269. if (this._animate && scene) {
  63270. this._time += scene.getAnimationRatio() * 0.03;
  63271. this.updateShaderUniforms();
  63272. }
  63273. _super.prototype.render.call(this, useCameraPostProcess);
  63274. };
  63275. CustomProceduralTexture.prototype.updateTextures = function () {
  63276. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63277. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63278. }
  63279. };
  63280. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63281. if (this._config) {
  63282. for (var j = 0; j < this._config.uniforms.length; j++) {
  63283. var uniform = this._config.uniforms[j];
  63284. switch (uniform.type) {
  63285. case "float":
  63286. this.setFloat(uniform.name, uniform.value);
  63287. break;
  63288. case "color3":
  63289. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63290. break;
  63291. case "color4":
  63292. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63293. break;
  63294. case "vector2":
  63295. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63296. break;
  63297. case "vector3":
  63298. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63299. break;
  63300. }
  63301. }
  63302. }
  63303. this.setFloat("time", this._time);
  63304. };
  63305. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63306. get: function () {
  63307. return this._animate;
  63308. },
  63309. set: function (value) {
  63310. this._animate = value;
  63311. },
  63312. enumerable: true,
  63313. configurable: true
  63314. });
  63315. return CustomProceduralTexture;
  63316. }(BABYLON.ProceduralTexture));
  63317. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63318. })(BABYLON || (BABYLON = {}));
  63319. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63320. var BABYLON;
  63321. (function (BABYLON) {
  63322. var FreeCameraGamepadInput = /** @class */ (function () {
  63323. function FreeCameraGamepadInput() {
  63324. this.gamepadAngularSensibility = 200;
  63325. this.gamepadMoveSensibility = 40;
  63326. // private members
  63327. this._cameraTransform = BABYLON.Matrix.Identity();
  63328. this._deltaTransform = BABYLON.Vector3.Zero();
  63329. this._vector3 = BABYLON.Vector3.Zero();
  63330. this._vector2 = BABYLON.Vector2.Zero();
  63331. }
  63332. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63333. var _this = this;
  63334. var manager = this.camera.getScene().gamepadManager;
  63335. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63336. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63337. // prioritize XBOX gamepads.
  63338. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63339. _this.gamepad = gamepad;
  63340. }
  63341. }
  63342. });
  63343. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63344. if (_this.gamepad === gamepad) {
  63345. _this.gamepad = null;
  63346. }
  63347. });
  63348. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63349. };
  63350. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63351. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63352. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63353. this.gamepad = null;
  63354. };
  63355. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63356. if (this.gamepad && this.gamepad.leftStick) {
  63357. var camera = this.camera;
  63358. var LSValues = this.gamepad.leftStick;
  63359. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63360. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63361. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63362. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63363. var RSValues = this.gamepad.rightStick;
  63364. if (RSValues) {
  63365. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63366. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63367. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63368. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63369. }
  63370. else {
  63371. RSValues = { x: 0, y: 0 };
  63372. }
  63373. if (!camera.rotationQuaternion) {
  63374. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63375. }
  63376. else {
  63377. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63378. }
  63379. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63380. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63381. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63382. camera.cameraDirection.addInPlace(this._deltaTransform);
  63383. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63384. camera.cameraRotation.addInPlace(this._vector2);
  63385. }
  63386. };
  63387. FreeCameraGamepadInput.prototype.getClassName = function () {
  63388. return "FreeCameraGamepadInput";
  63389. };
  63390. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63391. return "gamepad";
  63392. };
  63393. __decorate([
  63394. BABYLON.serialize()
  63395. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63396. __decorate([
  63397. BABYLON.serialize()
  63398. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63399. return FreeCameraGamepadInput;
  63400. }());
  63401. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63402. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63403. })(BABYLON || (BABYLON = {}));
  63404. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63405. var BABYLON;
  63406. (function (BABYLON) {
  63407. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63408. function ArcRotateCameraGamepadInput() {
  63409. this.gamepadRotationSensibility = 80;
  63410. this.gamepadMoveSensibility = 40;
  63411. }
  63412. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63413. var _this = this;
  63414. var manager = this.camera.getScene().gamepadManager;
  63415. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63416. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63417. // prioritize XBOX gamepads.
  63418. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63419. _this.gamepad = gamepad;
  63420. }
  63421. }
  63422. });
  63423. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63424. if (_this.gamepad === gamepad) {
  63425. _this.gamepad = null;
  63426. }
  63427. });
  63428. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63429. };
  63430. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63431. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63432. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63433. this.gamepad = null;
  63434. };
  63435. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63436. if (this.gamepad) {
  63437. var camera = this.camera;
  63438. var RSValues = this.gamepad.rightStick;
  63439. if (RSValues) {
  63440. if (RSValues.x != 0) {
  63441. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63442. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63443. camera.inertialAlphaOffset += normalizedRX;
  63444. }
  63445. }
  63446. if (RSValues.y != 0) {
  63447. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63448. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63449. camera.inertialBetaOffset += normalizedRY;
  63450. }
  63451. }
  63452. }
  63453. var LSValues = this.gamepad.leftStick;
  63454. if (LSValues && LSValues.y != 0) {
  63455. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63456. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63457. this.camera.inertialRadiusOffset -= normalizedLY;
  63458. }
  63459. }
  63460. }
  63461. };
  63462. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63463. return "ArcRotateCameraGamepadInput";
  63464. };
  63465. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63466. return "gamepad";
  63467. };
  63468. __decorate([
  63469. BABYLON.serialize()
  63470. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63471. __decorate([
  63472. BABYLON.serialize()
  63473. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63474. return ArcRotateCameraGamepadInput;
  63475. }());
  63476. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63477. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63478. })(BABYLON || (BABYLON = {}));
  63479. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63480. var BABYLON;
  63481. (function (BABYLON) {
  63482. var GamepadManager = /** @class */ (function () {
  63483. function GamepadManager(_scene) {
  63484. var _this = this;
  63485. this._scene = _scene;
  63486. this._babylonGamepads = [];
  63487. this._oneGamepadConnected = false;
  63488. this._isMonitoring = false;
  63489. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63490. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63491. this._gamepadEventSupported = false;
  63492. }
  63493. else {
  63494. this._gamepadEventSupported = 'GamepadEvent' in window;
  63495. this._gamepadSupport = (navigator.getGamepads ||
  63496. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63497. }
  63498. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63499. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63500. for (var i in _this._babylonGamepads) {
  63501. var gamepad = _this._babylonGamepads[i];
  63502. if (gamepad && gamepad._isConnected) {
  63503. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63504. }
  63505. }
  63506. });
  63507. this._onGamepadConnectedEvent = function (evt) {
  63508. var gamepad = evt.gamepad;
  63509. if (gamepad.index in _this._babylonGamepads) {
  63510. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63511. return;
  63512. }
  63513. }
  63514. var newGamepad;
  63515. if (_this._babylonGamepads[gamepad.index]) {
  63516. newGamepad = _this._babylonGamepads[gamepad.index];
  63517. newGamepad.browserGamepad = gamepad;
  63518. newGamepad._isConnected = true;
  63519. }
  63520. else {
  63521. newGamepad = _this._addNewGamepad(gamepad);
  63522. }
  63523. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63524. _this._startMonitoringGamepads();
  63525. };
  63526. this._onGamepadDisconnectedEvent = function (evt) {
  63527. var gamepad = evt.gamepad;
  63528. // Remove the gamepad from the list of gamepads to monitor.
  63529. for (var i in _this._babylonGamepads) {
  63530. if (_this._babylonGamepads[i].index === gamepad.index) {
  63531. var disconnectedGamepad = _this._babylonGamepads[i];
  63532. disconnectedGamepad._isConnected = false;
  63533. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63534. break;
  63535. }
  63536. }
  63537. };
  63538. if (this._gamepadSupport) {
  63539. //first add already-connected gamepads
  63540. this._updateGamepadObjects();
  63541. if (this._babylonGamepads.length) {
  63542. this._startMonitoringGamepads();
  63543. }
  63544. // Checking if the gamepad connected event is supported (like in Firefox)
  63545. if (this._gamepadEventSupported) {
  63546. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63547. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63548. }
  63549. else {
  63550. this._startMonitoringGamepads();
  63551. }
  63552. }
  63553. }
  63554. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63555. get: function () {
  63556. return this._babylonGamepads;
  63557. },
  63558. enumerable: true,
  63559. configurable: true
  63560. });
  63561. GamepadManager.prototype.getGamepadByType = function (type) {
  63562. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63563. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63564. var gamepad = _a[_i];
  63565. if (gamepad && gamepad.type === type) {
  63566. return gamepad;
  63567. }
  63568. }
  63569. return null;
  63570. };
  63571. GamepadManager.prototype.dispose = function () {
  63572. if (this._gamepadEventSupported) {
  63573. if (this._onGamepadConnectedEvent) {
  63574. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63575. }
  63576. if (this._onGamepadDisconnectedEvent) {
  63577. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63578. }
  63579. this._onGamepadConnectedEvent = null;
  63580. this._onGamepadDisconnectedEvent = null;
  63581. }
  63582. this._babylonGamepads.forEach(function (gamepad) {
  63583. gamepad.dispose();
  63584. });
  63585. this.onGamepadConnectedObservable.clear();
  63586. this.onGamepadDisconnectedObservable.clear();
  63587. this._oneGamepadConnected = false;
  63588. this._stopMonitoringGamepads();
  63589. this._babylonGamepads = [];
  63590. };
  63591. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63592. if (!this._oneGamepadConnected) {
  63593. this._oneGamepadConnected = true;
  63594. }
  63595. var newGamepad;
  63596. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63597. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63598. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63599. }
  63600. else if (gamepad.pose) {
  63601. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63602. }
  63603. else {
  63604. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63605. }
  63606. this._babylonGamepads[newGamepad.index] = newGamepad;
  63607. return newGamepad;
  63608. };
  63609. GamepadManager.prototype._startMonitoringGamepads = function () {
  63610. if (!this._isMonitoring) {
  63611. this._isMonitoring = true;
  63612. //back-comp
  63613. if (!this._scene) {
  63614. this._checkGamepadsStatus();
  63615. }
  63616. }
  63617. };
  63618. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63619. this._isMonitoring = false;
  63620. };
  63621. GamepadManager.prototype._checkGamepadsStatus = function () {
  63622. var _this = this;
  63623. // Hack to be compatible Chrome
  63624. this._updateGamepadObjects();
  63625. for (var i in this._babylonGamepads) {
  63626. var gamepad = this._babylonGamepads[i];
  63627. if (!gamepad || !gamepad.isConnected) {
  63628. continue;
  63629. }
  63630. gamepad.update();
  63631. }
  63632. if (this._isMonitoring && !this._scene) {
  63633. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63634. }
  63635. };
  63636. // This function is called only on Chrome, which does not properly support
  63637. // connection/disconnection events and forces you to recopy again the gamepad object
  63638. GamepadManager.prototype._updateGamepadObjects = function () {
  63639. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63640. for (var i = 0; i < gamepads.length; i++) {
  63641. if (gamepads[i]) {
  63642. if (!this._babylonGamepads[gamepads[i].index]) {
  63643. var newGamepad = this._addNewGamepad(gamepads[i]);
  63644. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63645. }
  63646. else {
  63647. // Forced to copy again this object for Chrome for unknown reason
  63648. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63649. if (!this._babylonGamepads[i].isConnected) {
  63650. this._babylonGamepads[i]._isConnected = true;
  63651. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63652. }
  63653. }
  63654. }
  63655. }
  63656. };
  63657. return GamepadManager;
  63658. }());
  63659. BABYLON.GamepadManager = GamepadManager;
  63660. })(BABYLON || (BABYLON = {}));
  63661. //# sourceMappingURL=babylon.gamepadManager.js.map
  63662. var BABYLON;
  63663. (function (BABYLON) {
  63664. var StickValues = /** @class */ (function () {
  63665. function StickValues(x, y) {
  63666. this.x = x;
  63667. this.y = y;
  63668. }
  63669. return StickValues;
  63670. }());
  63671. BABYLON.StickValues = StickValues;
  63672. var Gamepad = /** @class */ (function () {
  63673. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63674. if (leftStickX === void 0) { leftStickX = 0; }
  63675. if (leftStickY === void 0) { leftStickY = 1; }
  63676. if (rightStickX === void 0) { rightStickX = 2; }
  63677. if (rightStickY === void 0) { rightStickY = 3; }
  63678. this.id = id;
  63679. this.index = index;
  63680. this.browserGamepad = browserGamepad;
  63681. this._isConnected = true;
  63682. this._invertLeftStickY = false;
  63683. this.type = Gamepad.GAMEPAD;
  63684. this._leftStickAxisX = leftStickX;
  63685. this._leftStickAxisY = leftStickY;
  63686. this._rightStickAxisX = rightStickX;
  63687. this._rightStickAxisY = rightStickY;
  63688. if (this.browserGamepad.axes.length >= 2) {
  63689. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63690. }
  63691. if (this.browserGamepad.axes.length >= 4) {
  63692. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63693. }
  63694. }
  63695. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63696. get: function () {
  63697. return this._isConnected;
  63698. },
  63699. enumerable: true,
  63700. configurable: true
  63701. });
  63702. Gamepad.prototype.onleftstickchanged = function (callback) {
  63703. this._onleftstickchanged = callback;
  63704. };
  63705. Gamepad.prototype.onrightstickchanged = function (callback) {
  63706. this._onrightstickchanged = callback;
  63707. };
  63708. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63709. get: function () {
  63710. return this._leftStick;
  63711. },
  63712. set: function (newValues) {
  63713. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63714. this._onleftstickchanged(newValues);
  63715. }
  63716. this._leftStick = newValues;
  63717. },
  63718. enumerable: true,
  63719. configurable: true
  63720. });
  63721. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63722. get: function () {
  63723. return this._rightStick;
  63724. },
  63725. set: function (newValues) {
  63726. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63727. this._onrightstickchanged(newValues);
  63728. }
  63729. this._rightStick = newValues;
  63730. },
  63731. enumerable: true,
  63732. configurable: true
  63733. });
  63734. Gamepad.prototype.update = function () {
  63735. if (this._leftStick) {
  63736. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63737. if (this._invertLeftStickY) {
  63738. this.leftStick.y *= -1;
  63739. }
  63740. }
  63741. if (this._rightStick) {
  63742. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63743. }
  63744. };
  63745. Gamepad.prototype.dispose = function () {
  63746. };
  63747. Gamepad.GAMEPAD = 0;
  63748. Gamepad.GENERIC = 1;
  63749. Gamepad.XBOX = 2;
  63750. Gamepad.POSE_ENABLED = 3;
  63751. return Gamepad;
  63752. }());
  63753. BABYLON.Gamepad = Gamepad;
  63754. var GenericPad = /** @class */ (function (_super) {
  63755. __extends(GenericPad, _super);
  63756. function GenericPad(id, index, browserGamepad) {
  63757. var _this = _super.call(this, id, index, browserGamepad) || this;
  63758. _this.onButtonDownObservable = new BABYLON.Observable();
  63759. _this.onButtonUpObservable = new BABYLON.Observable();
  63760. _this.type = Gamepad.GENERIC;
  63761. _this._buttons = new Array(browserGamepad.buttons.length);
  63762. return _this;
  63763. }
  63764. GenericPad.prototype.onbuttondown = function (callback) {
  63765. this._onbuttondown = callback;
  63766. };
  63767. GenericPad.prototype.onbuttonup = function (callback) {
  63768. this._onbuttonup = callback;
  63769. };
  63770. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63771. if (newValue !== currentValue) {
  63772. if (newValue === 1) {
  63773. if (this._onbuttondown) {
  63774. this._onbuttondown(buttonIndex);
  63775. }
  63776. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63777. }
  63778. if (newValue === 0) {
  63779. if (this._onbuttonup) {
  63780. this._onbuttonup(buttonIndex);
  63781. }
  63782. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63783. }
  63784. }
  63785. return newValue;
  63786. };
  63787. GenericPad.prototype.update = function () {
  63788. _super.prototype.update.call(this);
  63789. for (var index = 0; index < this._buttons.length; index++) {
  63790. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63791. }
  63792. };
  63793. GenericPad.prototype.dispose = function () {
  63794. _super.prototype.dispose.call(this);
  63795. this.onButtonDownObservable.clear();
  63796. this.onButtonUpObservable.clear();
  63797. };
  63798. return GenericPad;
  63799. }(Gamepad));
  63800. BABYLON.GenericPad = GenericPad;
  63801. })(BABYLON || (BABYLON = {}));
  63802. //# sourceMappingURL=babylon.gamepad.js.map
  63803. var BABYLON;
  63804. (function (BABYLON) {
  63805. var Xbox360Button;
  63806. (function (Xbox360Button) {
  63807. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63808. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63809. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63810. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63811. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63812. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63813. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63814. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63815. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63816. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63817. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63818. var Xbox360Dpad;
  63819. (function (Xbox360Dpad) {
  63820. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63821. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63822. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63823. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63824. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63825. var Xbox360Pad = /** @class */ (function (_super) {
  63826. __extends(Xbox360Pad, _super);
  63827. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63828. if (xboxOne === void 0) { xboxOne = false; }
  63829. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63830. _this._leftTrigger = 0;
  63831. _this._rightTrigger = 0;
  63832. _this.onButtonDownObservable = new BABYLON.Observable();
  63833. _this.onButtonUpObservable = new BABYLON.Observable();
  63834. _this.onPadDownObservable = new BABYLON.Observable();
  63835. _this.onPadUpObservable = new BABYLON.Observable();
  63836. _this._buttonA = 0;
  63837. _this._buttonB = 0;
  63838. _this._buttonX = 0;
  63839. _this._buttonY = 0;
  63840. _this._buttonBack = 0;
  63841. _this._buttonStart = 0;
  63842. _this._buttonLB = 0;
  63843. _this._buttonRB = 0;
  63844. _this._buttonLeftStick = 0;
  63845. _this._buttonRightStick = 0;
  63846. _this._dPadUp = 0;
  63847. _this._dPadDown = 0;
  63848. _this._dPadLeft = 0;
  63849. _this._dPadRight = 0;
  63850. _this._isXboxOnePad = false;
  63851. _this.type = BABYLON.Gamepad.XBOX;
  63852. _this._isXboxOnePad = xboxOne;
  63853. return _this;
  63854. }
  63855. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63856. this._onlefttriggerchanged = callback;
  63857. };
  63858. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63859. this._onrighttriggerchanged = callback;
  63860. };
  63861. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63862. get: function () {
  63863. return this._leftTrigger;
  63864. },
  63865. set: function (newValue) {
  63866. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63867. this._onlefttriggerchanged(newValue);
  63868. }
  63869. this._leftTrigger = newValue;
  63870. },
  63871. enumerable: true,
  63872. configurable: true
  63873. });
  63874. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63875. get: function () {
  63876. return this._rightTrigger;
  63877. },
  63878. set: function (newValue) {
  63879. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63880. this._onrighttriggerchanged(newValue);
  63881. }
  63882. this._rightTrigger = newValue;
  63883. },
  63884. enumerable: true,
  63885. configurable: true
  63886. });
  63887. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63888. this._onbuttondown = callback;
  63889. };
  63890. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63891. this._onbuttonup = callback;
  63892. };
  63893. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63894. this._ondpaddown = callback;
  63895. };
  63896. Xbox360Pad.prototype.ondpadup = function (callback) {
  63897. this._ondpadup = callback;
  63898. };
  63899. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63900. if (newValue !== currentValue) {
  63901. if (newValue === 1) {
  63902. if (this._onbuttondown) {
  63903. this._onbuttondown(buttonType);
  63904. }
  63905. this.onButtonDownObservable.notifyObservers(buttonType);
  63906. }
  63907. if (newValue === 0) {
  63908. if (this._onbuttonup) {
  63909. this._onbuttonup(buttonType);
  63910. }
  63911. this.onButtonUpObservable.notifyObservers(buttonType);
  63912. }
  63913. }
  63914. return newValue;
  63915. };
  63916. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63917. if (newValue !== currentValue) {
  63918. if (newValue === 1) {
  63919. if (this._ondpaddown) {
  63920. this._ondpaddown(buttonType);
  63921. }
  63922. this.onPadDownObservable.notifyObservers(buttonType);
  63923. }
  63924. if (newValue === 0) {
  63925. if (this._ondpadup) {
  63926. this._ondpadup(buttonType);
  63927. }
  63928. this.onPadUpObservable.notifyObservers(buttonType);
  63929. }
  63930. }
  63931. return newValue;
  63932. };
  63933. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63934. get: function () {
  63935. return this._buttonA;
  63936. },
  63937. set: function (value) {
  63938. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63939. },
  63940. enumerable: true,
  63941. configurable: true
  63942. });
  63943. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63944. get: function () {
  63945. return this._buttonB;
  63946. },
  63947. set: function (value) {
  63948. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63949. },
  63950. enumerable: true,
  63951. configurable: true
  63952. });
  63953. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63954. get: function () {
  63955. return this._buttonX;
  63956. },
  63957. set: function (value) {
  63958. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63959. },
  63960. enumerable: true,
  63961. configurable: true
  63962. });
  63963. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63964. get: function () {
  63965. return this._buttonY;
  63966. },
  63967. set: function (value) {
  63968. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63969. },
  63970. enumerable: true,
  63971. configurable: true
  63972. });
  63973. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63974. get: function () {
  63975. return this._buttonStart;
  63976. },
  63977. set: function (value) {
  63978. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63979. },
  63980. enumerable: true,
  63981. configurable: true
  63982. });
  63983. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63984. get: function () {
  63985. return this._buttonBack;
  63986. },
  63987. set: function (value) {
  63988. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63989. },
  63990. enumerable: true,
  63991. configurable: true
  63992. });
  63993. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63994. get: function () {
  63995. return this._buttonLB;
  63996. },
  63997. set: function (value) {
  63998. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63999. },
  64000. enumerable: true,
  64001. configurable: true
  64002. });
  64003. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64004. get: function () {
  64005. return this._buttonRB;
  64006. },
  64007. set: function (value) {
  64008. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64009. },
  64010. enumerable: true,
  64011. configurable: true
  64012. });
  64013. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64014. get: function () {
  64015. return this._buttonLeftStick;
  64016. },
  64017. set: function (value) {
  64018. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64019. },
  64020. enumerable: true,
  64021. configurable: true
  64022. });
  64023. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64024. get: function () {
  64025. return this._buttonRightStick;
  64026. },
  64027. set: function (value) {
  64028. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64029. },
  64030. enumerable: true,
  64031. configurable: true
  64032. });
  64033. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64034. get: function () {
  64035. return this._dPadUp;
  64036. },
  64037. set: function (value) {
  64038. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64039. },
  64040. enumerable: true,
  64041. configurable: true
  64042. });
  64043. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64044. get: function () {
  64045. return this._dPadDown;
  64046. },
  64047. set: function (value) {
  64048. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64049. },
  64050. enumerable: true,
  64051. configurable: true
  64052. });
  64053. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64054. get: function () {
  64055. return this._dPadLeft;
  64056. },
  64057. set: function (value) {
  64058. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64064. get: function () {
  64065. return this._dPadRight;
  64066. },
  64067. set: function (value) {
  64068. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64069. },
  64070. enumerable: true,
  64071. configurable: true
  64072. });
  64073. Xbox360Pad.prototype.update = function () {
  64074. _super.prototype.update.call(this);
  64075. if (this._isXboxOnePad) {
  64076. this.buttonA = this.browserGamepad.buttons[0].value;
  64077. this.buttonB = this.browserGamepad.buttons[1].value;
  64078. this.buttonX = this.browserGamepad.buttons[2].value;
  64079. this.buttonY = this.browserGamepad.buttons[3].value;
  64080. this.buttonLB = this.browserGamepad.buttons[4].value;
  64081. this.buttonRB = this.browserGamepad.buttons[5].value;
  64082. this.leftTrigger = this.browserGamepad.axes[2];
  64083. this.rightTrigger = this.browserGamepad.axes[5];
  64084. this.buttonBack = this.browserGamepad.buttons[9].value;
  64085. this.buttonStart = this.browserGamepad.buttons[8].value;
  64086. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64087. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64088. this.dPadUp = this.browserGamepad.buttons[11].value;
  64089. this.dPadDown = this.browserGamepad.buttons[12].value;
  64090. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64091. this.dPadRight = this.browserGamepad.buttons[14].value;
  64092. }
  64093. else {
  64094. this.buttonA = this.browserGamepad.buttons[0].value;
  64095. this.buttonB = this.browserGamepad.buttons[1].value;
  64096. this.buttonX = this.browserGamepad.buttons[2].value;
  64097. this.buttonY = this.browserGamepad.buttons[3].value;
  64098. this.buttonLB = this.browserGamepad.buttons[4].value;
  64099. this.buttonRB = this.browserGamepad.buttons[5].value;
  64100. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64101. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64102. this.buttonBack = this.browserGamepad.buttons[8].value;
  64103. this.buttonStart = this.browserGamepad.buttons[9].value;
  64104. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64105. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64106. this.dPadUp = this.browserGamepad.buttons[12].value;
  64107. this.dPadDown = this.browserGamepad.buttons[13].value;
  64108. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64109. this.dPadRight = this.browserGamepad.buttons[15].value;
  64110. }
  64111. };
  64112. Xbox360Pad.prototype.dispose = function () {
  64113. _super.prototype.dispose.call(this);
  64114. this.onButtonDownObservable.clear();
  64115. this.onButtonUpObservable.clear();
  64116. this.onPadDownObservable.clear();
  64117. this.onPadUpObservable.clear();
  64118. };
  64119. return Xbox360Pad;
  64120. }(BABYLON.Gamepad));
  64121. BABYLON.Xbox360Pad = Xbox360Pad;
  64122. })(BABYLON || (BABYLON = {}));
  64123. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64124. var BABYLON;
  64125. (function (BABYLON) {
  64126. var PoseEnabledControllerType;
  64127. (function (PoseEnabledControllerType) {
  64128. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64129. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64130. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64131. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64132. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64133. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64134. var PoseEnabledControllerHelper = /** @class */ (function () {
  64135. function PoseEnabledControllerHelper() {
  64136. }
  64137. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64138. // Oculus Touch
  64139. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64140. return new BABYLON.OculusTouchController(vrGamepad);
  64141. }
  64142. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64143. return new BABYLON.WindowsMotionController(vrGamepad);
  64144. }
  64145. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64146. return new BABYLON.ViveController(vrGamepad);
  64147. }
  64148. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64149. return new BABYLON.GearVRController(vrGamepad);
  64150. }
  64151. else {
  64152. return new BABYLON.GenericController(vrGamepad);
  64153. }
  64154. };
  64155. return PoseEnabledControllerHelper;
  64156. }());
  64157. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64158. var PoseEnabledController = /** @class */ (function (_super) {
  64159. __extends(PoseEnabledController, _super);
  64160. function PoseEnabledController(browserGamepad) {
  64161. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64162. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64163. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64164. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64165. // Represents device position and rotation in babylon space
  64166. _this.devicePosition = BABYLON.Vector3.Zero();
  64167. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64168. _this.deviceScaleFactor = 1;
  64169. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64170. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64171. _this._workingMatrix = BABYLON.Matrix.Identity();
  64172. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64173. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64174. _this.position = BABYLON.Vector3.Zero();
  64175. _this.rotationQuaternion = new BABYLON.Quaternion();
  64176. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64177. _this._calculatedRotation = new BABYLON.Quaternion();
  64178. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64179. return _this;
  64180. }
  64181. PoseEnabledController.prototype.update = function () {
  64182. _super.prototype.update.call(this);
  64183. var pose = this.browserGamepad.pose;
  64184. this.updateFromDevice(pose);
  64185. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64186. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64187. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64188. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64189. if (this._mesh) {
  64190. this._mesh.position.copyFrom(this.devicePosition);
  64191. if (this._mesh.rotationQuaternion) {
  64192. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64193. }
  64194. }
  64195. };
  64196. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64197. if (poseData) {
  64198. this.rawPose = poseData;
  64199. if (poseData.position) {
  64200. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64201. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64202. this._deviceRoomPosition.z *= -1;
  64203. }
  64204. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64205. this._calculatedPosition.addInPlace(this.position);
  64206. }
  64207. var pose = this.rawPose;
  64208. if (poseData.orientation && pose.orientation) {
  64209. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64210. if (this._mesh) {
  64211. if (this._mesh.getScene().useRightHandedSystem) {
  64212. this._deviceRoomRotationQuaternion.z *= -1;
  64213. this._deviceRoomRotationQuaternion.w *= -1;
  64214. }
  64215. else {
  64216. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64217. }
  64218. }
  64219. // if the camera is set, rotate to the camera's rotation
  64220. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64221. }
  64222. }
  64223. };
  64224. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64225. if (this._mesh) {
  64226. this._mesh.parent = null;
  64227. }
  64228. this._mesh = mesh;
  64229. if (this._poseControlledCamera) {
  64230. this._mesh.parent = this._poseControlledCamera;
  64231. }
  64232. if (!this._mesh.rotationQuaternion) {
  64233. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64234. }
  64235. };
  64236. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64237. this._poseControlledCamera = camera;
  64238. if (this._mesh) {
  64239. this._mesh.parent = this._poseControlledCamera;
  64240. }
  64241. };
  64242. PoseEnabledController.prototype.dispose = function () {
  64243. if (this._mesh) {
  64244. this._mesh.dispose();
  64245. }
  64246. this._mesh = null;
  64247. _super.prototype.dispose.call(this);
  64248. };
  64249. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64250. get: function () {
  64251. return this._mesh;
  64252. },
  64253. enumerable: true,
  64254. configurable: true
  64255. });
  64256. PoseEnabledController.prototype.getForwardRay = function (length) {
  64257. if (length === void 0) { length = 100; }
  64258. if (!this.mesh) {
  64259. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64260. }
  64261. var m = this.mesh.getWorldMatrix();
  64262. var origin = m.getTranslation();
  64263. var forward = new BABYLON.Vector3(0, 0, -1);
  64264. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64265. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64266. return new BABYLON.Ray(origin, direction, length);
  64267. };
  64268. return PoseEnabledController;
  64269. }(BABYLON.Gamepad));
  64270. BABYLON.PoseEnabledController = PoseEnabledController;
  64271. })(BABYLON || (BABYLON = {}));
  64272. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64273. var BABYLON;
  64274. (function (BABYLON) {
  64275. var WebVRController = /** @class */ (function (_super) {
  64276. __extends(WebVRController, _super);
  64277. function WebVRController(vrGamepad) {
  64278. var _this = _super.call(this, vrGamepad) || this;
  64279. // Observables
  64280. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64281. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64282. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64283. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64284. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64285. _this.pad = { x: 0, y: 0 };
  64286. // avoid GC, store state in a tmp object
  64287. _this._changes = {
  64288. pressChanged: false,
  64289. touchChanged: false,
  64290. valueChanged: false,
  64291. changed: false
  64292. };
  64293. _this._buttons = new Array(vrGamepad.buttons.length);
  64294. _this.hand = vrGamepad.hand;
  64295. return _this;
  64296. }
  64297. WebVRController.prototype.onButtonStateChange = function (callback) {
  64298. this._onButtonStateChange = callback;
  64299. };
  64300. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64301. get: function () {
  64302. return this._defaultModel;
  64303. },
  64304. enumerable: true,
  64305. configurable: true
  64306. });
  64307. WebVRController.prototype.update = function () {
  64308. _super.prototype.update.call(this);
  64309. for (var index = 0; index < this._buttons.length; index++) {
  64310. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64311. }
  64312. ;
  64313. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64314. this.pad.x = this.leftStick.x;
  64315. this.pad.y = this.leftStick.y;
  64316. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64317. }
  64318. };
  64319. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64320. if (!newState) {
  64321. newState = {
  64322. pressed: false,
  64323. touched: false,
  64324. value: 0
  64325. };
  64326. }
  64327. if (!currentState) {
  64328. this._buttons[buttonIndex] = {
  64329. pressed: newState.pressed,
  64330. touched: newState.touched,
  64331. value: newState.value
  64332. };
  64333. return;
  64334. }
  64335. this._checkChanges(newState, currentState);
  64336. if (this._changes.changed) {
  64337. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64338. this.handleButtonChange(buttonIndex, newState, this._changes);
  64339. }
  64340. this._buttons[buttonIndex].pressed = newState.pressed;
  64341. this._buttons[buttonIndex].touched = newState.touched;
  64342. // oculus triggers are never 0, thou not touched.
  64343. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64344. };
  64345. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64346. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64347. this._changes.touchChanged = newState.touched !== currentState.touched;
  64348. this._changes.valueChanged = newState.value !== currentState.value;
  64349. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64350. return this._changes;
  64351. };
  64352. WebVRController.prototype.dispose = function () {
  64353. _super.prototype.dispose.call(this);
  64354. this.onTriggerStateChangedObservable.clear();
  64355. this.onMainButtonStateChangedObservable.clear();
  64356. this.onSecondaryButtonStateChangedObservable.clear();
  64357. this.onPadStateChangedObservable.clear();
  64358. this.onPadValuesChangedObservable.clear();
  64359. };
  64360. return WebVRController;
  64361. }(BABYLON.PoseEnabledController));
  64362. BABYLON.WebVRController = WebVRController;
  64363. })(BABYLON || (BABYLON = {}));
  64364. //# sourceMappingURL=babylon.webVRController.js.map
  64365. var BABYLON;
  64366. (function (BABYLON) {
  64367. var OculusTouchController = /** @class */ (function (_super) {
  64368. __extends(OculusTouchController, _super);
  64369. function OculusTouchController(vrGamepad) {
  64370. var _this = _super.call(this, vrGamepad) || this;
  64371. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64372. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64373. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64374. return _this;
  64375. }
  64376. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64377. var _this = this;
  64378. var meshName;
  64379. // Hand
  64380. if (this.hand === 'left') {
  64381. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64382. }
  64383. else {
  64384. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64385. }
  64386. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64387. /*
  64388. Parent Mesh name: oculus_touch_left
  64389. - body
  64390. - trigger
  64391. - thumbstick
  64392. - grip
  64393. - button_y
  64394. - button_x
  64395. - button_enter
  64396. */
  64397. _this._defaultModel = newMeshes[1];
  64398. _this.attachToMesh(_this._defaultModel);
  64399. if (meshLoaded) {
  64400. meshLoaded(_this._defaultModel);
  64401. }
  64402. });
  64403. };
  64404. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64405. // helper getters for left and right hand.
  64406. get: function () {
  64407. if (this.hand === 'right') {
  64408. return this.onMainButtonStateChangedObservable;
  64409. }
  64410. else {
  64411. throw new Error('No A button on left hand');
  64412. }
  64413. },
  64414. enumerable: true,
  64415. configurable: true
  64416. });
  64417. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64418. get: function () {
  64419. if (this.hand === 'right') {
  64420. return this.onSecondaryButtonStateChangedObservable;
  64421. }
  64422. else {
  64423. throw new Error('No B button on left hand');
  64424. }
  64425. },
  64426. enumerable: true,
  64427. configurable: true
  64428. });
  64429. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64430. get: function () {
  64431. if (this.hand === 'left') {
  64432. return this.onMainButtonStateChangedObservable;
  64433. }
  64434. else {
  64435. throw new Error('No X button on right hand');
  64436. }
  64437. },
  64438. enumerable: true,
  64439. configurable: true
  64440. });
  64441. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64442. get: function () {
  64443. if (this.hand === 'left') {
  64444. return this.onSecondaryButtonStateChangedObservable;
  64445. }
  64446. else {
  64447. throw new Error('No Y button on right hand');
  64448. }
  64449. },
  64450. enumerable: true,
  64451. configurable: true
  64452. });
  64453. /*
  64454. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64455. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64456. 2) secondary trigger (same)
  64457. 3) A (right) X (left), touch, pressed = value
  64458. 4) B / Y
  64459. 5) thumb rest
  64460. */
  64461. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64462. var notifyObject = state; //{ state: state, changes: changes };
  64463. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64464. switch (buttonIdx) {
  64465. case 0:
  64466. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64467. return;
  64468. case 1:// index trigger
  64469. if (this._defaultModel) {
  64470. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64471. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64472. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64473. }
  64474. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64475. return;
  64476. case 2:// secondary trigger
  64477. if (this._defaultModel) {
  64478. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64479. }
  64480. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64481. return;
  64482. case 3:
  64483. if (this._defaultModel) {
  64484. if (notifyObject.pressed) {
  64485. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64486. }
  64487. else {
  64488. (this._defaultModel.getChildren()[1]).position.y = 0;
  64489. }
  64490. }
  64491. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64492. return;
  64493. case 4:
  64494. if (this._defaultModel) {
  64495. if (notifyObject.pressed) {
  64496. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64497. }
  64498. else {
  64499. (this._defaultModel.getChildren()[2]).position.y = 0;
  64500. }
  64501. }
  64502. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64503. return;
  64504. case 5:
  64505. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64506. return;
  64507. }
  64508. };
  64509. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64510. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64511. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64512. return OculusTouchController;
  64513. }(BABYLON.WebVRController));
  64514. BABYLON.OculusTouchController = OculusTouchController;
  64515. })(BABYLON || (BABYLON = {}));
  64516. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64517. var BABYLON;
  64518. (function (BABYLON) {
  64519. var ViveController = /** @class */ (function (_super) {
  64520. __extends(ViveController, _super);
  64521. function ViveController(vrGamepad) {
  64522. var _this = _super.call(this, vrGamepad) || this;
  64523. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64524. _this._invertLeftStickY = true;
  64525. return _this;
  64526. }
  64527. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64528. var _this = this;
  64529. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64530. /*
  64531. Parent Mesh name: ViveWand
  64532. - body
  64533. - r_gripper
  64534. - l_gripper
  64535. - menu_button
  64536. - system_button
  64537. - trackpad
  64538. - trigger
  64539. - LED
  64540. */
  64541. _this._defaultModel = newMeshes[1];
  64542. _this.attachToMesh(_this._defaultModel);
  64543. if (meshLoaded) {
  64544. meshLoaded(_this._defaultModel);
  64545. }
  64546. });
  64547. };
  64548. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64549. get: function () {
  64550. return this.onMainButtonStateChangedObservable;
  64551. },
  64552. enumerable: true,
  64553. configurable: true
  64554. });
  64555. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64556. get: function () {
  64557. return this.onMainButtonStateChangedObservable;
  64558. },
  64559. enumerable: true,
  64560. configurable: true
  64561. });
  64562. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64563. get: function () {
  64564. return this.onSecondaryButtonStateChangedObservable;
  64565. },
  64566. enumerable: true,
  64567. configurable: true
  64568. });
  64569. /**
  64570. * Vive mapping:
  64571. * 0: touchpad
  64572. * 1: trigger
  64573. * 2: left AND right buttons
  64574. * 3: menu button
  64575. */
  64576. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64577. var notifyObject = state; //{ state: state, changes: changes };
  64578. switch (buttonIdx) {
  64579. case 0:
  64580. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64581. return;
  64582. case 1:// index trigger
  64583. if (this._defaultModel) {
  64584. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64585. }
  64586. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64587. return;
  64588. case 2:// left AND right button
  64589. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64590. return;
  64591. case 3:
  64592. if (this._defaultModel) {
  64593. if (notifyObject.pressed) {
  64594. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64595. }
  64596. else {
  64597. (this._defaultModel.getChildren()[2]).position.y = 0;
  64598. }
  64599. }
  64600. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64601. return;
  64602. }
  64603. };
  64604. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64605. ViveController.MODEL_FILENAME = 'wand.babylon';
  64606. return ViveController;
  64607. }(BABYLON.WebVRController));
  64608. BABYLON.ViveController = ViveController;
  64609. })(BABYLON || (BABYLON = {}));
  64610. //# sourceMappingURL=babylon.viveController.js.map
  64611. var BABYLON;
  64612. (function (BABYLON) {
  64613. var GenericController = /** @class */ (function (_super) {
  64614. __extends(GenericController, _super);
  64615. function GenericController(vrGamepad) {
  64616. return _super.call(this, vrGamepad) || this;
  64617. }
  64618. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64619. var _this = this;
  64620. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64621. _this._defaultModel = newMeshes[1];
  64622. _this.attachToMesh(_this._defaultModel);
  64623. if (meshLoaded) {
  64624. meshLoaded(_this._defaultModel);
  64625. }
  64626. });
  64627. };
  64628. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64629. console.log("Button id: " + buttonIdx + "state: ");
  64630. console.dir(state);
  64631. };
  64632. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64633. GenericController.MODEL_FILENAME = 'generic.babylon';
  64634. return GenericController;
  64635. }(BABYLON.WebVRController));
  64636. BABYLON.GenericController = GenericController;
  64637. })(BABYLON || (BABYLON = {}));
  64638. //# sourceMappingURL=babylon.genericController.js.map
  64639. var BABYLON;
  64640. (function (BABYLON) {
  64641. var LoadedMeshInfo = /** @class */ (function () {
  64642. function LoadedMeshInfo() {
  64643. this.buttonMeshes = {};
  64644. this.axisMeshes = {};
  64645. }
  64646. return LoadedMeshInfo;
  64647. }());
  64648. var WindowsMotionController = /** @class */ (function (_super) {
  64649. __extends(WindowsMotionController, _super);
  64650. function WindowsMotionController(vrGamepad) {
  64651. var _this = _super.call(this, vrGamepad) || this;
  64652. _this._mapping = {
  64653. // Semantic button names
  64654. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64655. // A mapping of the button name to glTF model node name
  64656. // that should be transformed by button value.
  64657. buttonMeshNames: {
  64658. 'trigger': 'SELECT',
  64659. 'menu': 'MENU',
  64660. 'grip': 'GRASP',
  64661. 'thumbstick': 'THUMBSTICK_PRESS',
  64662. 'trackpad': 'TOUCHPAD_PRESS'
  64663. },
  64664. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64665. buttonObservableNames: {
  64666. 'trigger': 'onTriggerStateChangedObservable',
  64667. 'menu': 'onSecondaryButtonStateChangedObservable',
  64668. 'grip': 'onMainButtonStateChangedObservable',
  64669. 'thumbstick': 'onPadStateChangedObservable',
  64670. 'trackpad': 'onTrackpadChangedObservable'
  64671. },
  64672. // A mapping of the axis name to glTF model node name
  64673. // that should be transformed by axis value.
  64674. // This array mirrors the browserGamepad.axes array, such that
  64675. // the mesh corresponding to axis 0 is in this array index 0.
  64676. axisMeshNames: [
  64677. 'THUMBSTICK_X',
  64678. 'THUMBSTICK_Y',
  64679. 'TOUCHPAD_TOUCH_X',
  64680. 'TOUCHPAD_TOUCH_Y'
  64681. ],
  64682. pointingPoseMeshName: 'POINTING_POSE'
  64683. };
  64684. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64685. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64686. _this.trackpad = { x: 0, y: 0 };
  64687. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64688. _this._loadedMeshInfo = null;
  64689. return _this;
  64690. }
  64691. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64692. get: function () {
  64693. return this.onTriggerStateChangedObservable;
  64694. },
  64695. enumerable: true,
  64696. configurable: true
  64697. });
  64698. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64699. get: function () {
  64700. return this.onSecondaryButtonStateChangedObservable;
  64701. },
  64702. enumerable: true,
  64703. configurable: true
  64704. });
  64705. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64706. get: function () {
  64707. return this.onMainButtonStateChangedObservable;
  64708. },
  64709. enumerable: true,
  64710. configurable: true
  64711. });
  64712. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64713. get: function () {
  64714. return this.onPadStateChangedObservable;
  64715. },
  64716. enumerable: true,
  64717. configurable: true
  64718. });
  64719. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64720. get: function () {
  64721. return this.onTrackpadChangedObservable;
  64722. },
  64723. enumerable: true,
  64724. configurable: true
  64725. });
  64726. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64727. get: function () {
  64728. return this.onTrackpadValuesChangedObservable;
  64729. },
  64730. enumerable: true,
  64731. configurable: true
  64732. });
  64733. /**
  64734. * Called once per frame by the engine.
  64735. */
  64736. WindowsMotionController.prototype.update = function () {
  64737. _super.prototype.update.call(this);
  64738. // Only need to animate axes if there is a loaded mesh
  64739. if (this._loadedMeshInfo) {
  64740. if (this.browserGamepad.axes) {
  64741. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64742. this.trackpad.x = this.browserGamepad["axes"][2];
  64743. this.trackpad.y = this.browserGamepad["axes"][3];
  64744. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64745. }
  64746. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64747. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64748. }
  64749. }
  64750. }
  64751. };
  64752. /**
  64753. * Called once for each button that changed state since the last frame
  64754. * @param buttonIdx Which button index changed
  64755. * @param state New state of the button
  64756. * @param changes Which properties on the state changed since last frame
  64757. */
  64758. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64759. var buttonName = this._mapping.buttons[buttonIdx];
  64760. if (!buttonName) {
  64761. return;
  64762. }
  64763. // Only emit events for buttons that we know how to map from index to name
  64764. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64765. if (observable) {
  64766. observable.notifyObservers(state);
  64767. }
  64768. this.lerpButtonTransform(buttonName, state.value);
  64769. };
  64770. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64771. // If there is no loaded mesh, there is nothing to transform.
  64772. if (!this._loadedMeshInfo) {
  64773. return;
  64774. }
  64775. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64776. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64777. return;
  64778. }
  64779. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64780. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64781. };
  64782. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64783. if (!this._loadedMeshInfo) {
  64784. return;
  64785. }
  64786. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64787. if (!meshInfo) {
  64788. return;
  64789. }
  64790. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64791. return;
  64792. }
  64793. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64794. var lerpValue = axisValue * 0.5 + 0.5;
  64795. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64796. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64797. };
  64798. /**
  64799. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64800. * @param scene scene in which to add meshes
  64801. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64802. */
  64803. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64804. var _this = this;
  64805. if (forceDefault === void 0) { forceDefault = false; }
  64806. var path;
  64807. var filename;
  64808. // Checking if GLB loader is present
  64809. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64810. // Determine the device specific folder based on the ID suffix
  64811. var device = 'default';
  64812. if (this.id && !forceDefault) {
  64813. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64814. device = ((match && match[0]) || device);
  64815. }
  64816. // Hand
  64817. if (this.hand === 'left') {
  64818. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64819. }
  64820. else {
  64821. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64822. }
  64823. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64824. }
  64825. else {
  64826. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64827. path = BABYLON.GenericController.MODEL_BASE_URL;
  64828. filename = BABYLON.GenericController.MODEL_FILENAME;
  64829. }
  64830. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64831. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64832. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64833. if (!_this._loadedMeshInfo) {
  64834. return;
  64835. }
  64836. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64837. _this.attachToMesh(_this._defaultModel);
  64838. if (meshLoaded) {
  64839. meshLoaded(_this._defaultModel);
  64840. }
  64841. }, null, function (scene, message) {
  64842. BABYLON.Tools.Log(message);
  64843. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64844. if (!forceDefault) {
  64845. _this.initControllerMesh(scene, meshLoaded, true);
  64846. }
  64847. });
  64848. };
  64849. /**
  64850. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64851. * can be transformed by button presses and axes values, based on this._mapping.
  64852. *
  64853. * @param scene scene in which the meshes exist
  64854. * @param meshes list of meshes that make up the controller model to process
  64855. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64856. */
  64857. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64858. var loadedMeshInfo = null;
  64859. // Create a new mesh to contain the glTF hierarchy
  64860. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64861. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64862. var childMesh = null;
  64863. for (var i = 0; i < meshes.length; i++) {
  64864. var mesh = meshes[i];
  64865. if (!mesh.parent) {
  64866. // Exclude controller meshes from picking results
  64867. mesh.isPickable = false;
  64868. // Handle root node, attach to the new parentMesh
  64869. childMesh = mesh;
  64870. break;
  64871. }
  64872. }
  64873. if (childMesh) {
  64874. childMesh.setParent(parentMesh);
  64875. // Create our mesh info. Note that this method will always return non-null.
  64876. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64877. }
  64878. else {
  64879. BABYLON.Tools.Warn('Could not find root node in model file.');
  64880. }
  64881. return loadedMeshInfo;
  64882. };
  64883. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64884. var loadedMeshInfo = new LoadedMeshInfo();
  64885. var i;
  64886. loadedMeshInfo.rootNode = rootNode;
  64887. // Reset the caches
  64888. loadedMeshInfo.buttonMeshes = {};
  64889. loadedMeshInfo.axisMeshes = {};
  64890. // Button Meshes
  64891. for (i = 0; i < this._mapping.buttons.length; i++) {
  64892. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64893. if (!buttonMeshName) {
  64894. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64895. continue;
  64896. }
  64897. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64898. if (!buttonMesh) {
  64899. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64900. continue;
  64901. }
  64902. var buttonMeshInfo = {
  64903. index: i,
  64904. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64905. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64906. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64907. };
  64908. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64909. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64910. }
  64911. else {
  64912. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64913. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64914. '(VALUE: ' + !!buttonMeshInfo.value +
  64915. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64916. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64917. ')');
  64918. }
  64919. }
  64920. // Axis Meshes
  64921. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64922. var axisMeshName = this._mapping.axisMeshNames[i];
  64923. if (!axisMeshName) {
  64924. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64925. continue;
  64926. }
  64927. var axisMesh = getChildByName(rootNode, axisMeshName);
  64928. if (!axisMesh) {
  64929. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64930. continue;
  64931. }
  64932. var axisMeshInfo = {
  64933. index: i,
  64934. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64935. min: getImmediateChildByName(axisMesh, 'MIN'),
  64936. max: getImmediateChildByName(axisMesh, 'MAX')
  64937. };
  64938. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64939. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64940. }
  64941. else {
  64942. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64943. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64944. '(VALUE: ' + !!axisMeshInfo.value +
  64945. ', MIN: ' + !!axisMeshInfo.min +
  64946. ', MAX:' + !!axisMeshInfo.max +
  64947. ')');
  64948. }
  64949. }
  64950. // Pointing Ray
  64951. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64952. if (!loadedMeshInfo.pointingPoseNode) {
  64953. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64954. }
  64955. return loadedMeshInfo;
  64956. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64957. function getChildByName(node, name) {
  64958. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64959. }
  64960. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64961. function getImmediateChildByName(node, name) {
  64962. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64963. }
  64964. };
  64965. WindowsMotionController.prototype.getForwardRay = function (length) {
  64966. if (length === void 0) { length = 100; }
  64967. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64968. return _super.prototype.getForwardRay.call(this, length);
  64969. }
  64970. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64971. var origin = m.getTranslation();
  64972. var forward = new BABYLON.Vector3(0, 0, -1);
  64973. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64974. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64975. return new BABYLON.Ray(origin, direction, length);
  64976. };
  64977. WindowsMotionController.prototype.dispose = function () {
  64978. _super.prototype.dispose.call(this);
  64979. this.onTrackpadChangedObservable.clear();
  64980. };
  64981. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64982. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64983. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64984. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64985. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64986. return WindowsMotionController;
  64987. }(BABYLON.WebVRController));
  64988. BABYLON.WindowsMotionController = WindowsMotionController;
  64989. })(BABYLON || (BABYLON = {}));
  64990. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64991. var BABYLON;
  64992. (function (BABYLON) {
  64993. var GearVRController = /** @class */ (function (_super) {
  64994. __extends(GearVRController, _super);
  64995. function GearVRController(vrGamepad) {
  64996. var _this = _super.call(this, vrGamepad) || this;
  64997. _this._buttonIndexToObservableNameMap = [
  64998. 'onTrackpadChangedObservable',
  64999. 'onTriggerStateChangedObservable' // Trigger
  65000. ];
  65001. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65002. return _this;
  65003. }
  65004. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65005. var _this = this;
  65006. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65007. _this._defaultModel = newMeshes[1];
  65008. _this.attachToMesh(_this._defaultModel);
  65009. if (meshLoaded) {
  65010. meshLoaded(_this._defaultModel);
  65011. }
  65012. });
  65013. };
  65014. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65015. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65016. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65017. // Only emit events for buttons that we know how to map from index to observable
  65018. var observable = this[observableName];
  65019. if (observable) {
  65020. observable.notifyObservers(state);
  65021. }
  65022. }
  65023. };
  65024. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65025. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65026. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65027. return GearVRController;
  65028. }(BABYLON.WebVRController));
  65029. BABYLON.GearVRController = GearVRController;
  65030. })(BABYLON || (BABYLON = {}));
  65031. //# sourceMappingURL=babylon.gearVRController.js.map
  65032. var BABYLON;
  65033. (function (BABYLON) {
  65034. var FollowCamera = /** @class */ (function (_super) {
  65035. __extends(FollowCamera, _super);
  65036. function FollowCamera(name, position, scene, lockedTarget) {
  65037. if (lockedTarget === void 0) { lockedTarget = null; }
  65038. var _this = _super.call(this, name, position, scene) || this;
  65039. _this.radius = 12;
  65040. _this.rotationOffset = 0;
  65041. _this.heightOffset = 4;
  65042. _this.cameraAcceleration = 0.05;
  65043. _this.maxCameraSpeed = 20;
  65044. _this.lockedTarget = lockedTarget;
  65045. return _this;
  65046. }
  65047. FollowCamera.prototype.getRadians = function (degrees) {
  65048. return degrees * Math.PI / 180;
  65049. };
  65050. FollowCamera.prototype.follow = function (cameraTarget) {
  65051. if (!cameraTarget)
  65052. return;
  65053. var yRotation;
  65054. if (cameraTarget.rotationQuaternion) {
  65055. var rotMatrix = new BABYLON.Matrix();
  65056. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65057. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65058. }
  65059. else {
  65060. yRotation = cameraTarget.rotation.y;
  65061. }
  65062. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65063. var targetPosition = cameraTarget.getAbsolutePosition();
  65064. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65065. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65066. var dx = targetX - this.position.x;
  65067. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65068. var dz = (targetZ) - this.position.z;
  65069. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65070. var vy = dy * this.cameraAcceleration;
  65071. var vz = dz * this.cameraAcceleration * 2;
  65072. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65073. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65074. }
  65075. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65076. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65077. }
  65078. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65079. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65080. }
  65081. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65082. this.setTarget(targetPosition);
  65083. };
  65084. FollowCamera.prototype._checkInputs = function () {
  65085. _super.prototype._checkInputs.call(this);
  65086. if (this.lockedTarget) {
  65087. this.follow(this.lockedTarget);
  65088. }
  65089. };
  65090. FollowCamera.prototype.getClassName = function () {
  65091. return "FollowCamera";
  65092. };
  65093. __decorate([
  65094. BABYLON.serialize()
  65095. ], FollowCamera.prototype, "radius", void 0);
  65096. __decorate([
  65097. BABYLON.serialize()
  65098. ], FollowCamera.prototype, "rotationOffset", void 0);
  65099. __decorate([
  65100. BABYLON.serialize()
  65101. ], FollowCamera.prototype, "heightOffset", void 0);
  65102. __decorate([
  65103. BABYLON.serialize()
  65104. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65105. __decorate([
  65106. BABYLON.serialize()
  65107. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65108. __decorate([
  65109. BABYLON.serializeAsMeshReference("lockedTargetId")
  65110. ], FollowCamera.prototype, "lockedTarget", void 0);
  65111. return FollowCamera;
  65112. }(BABYLON.TargetCamera));
  65113. BABYLON.FollowCamera = FollowCamera;
  65114. var ArcFollowCamera = /** @class */ (function (_super) {
  65115. __extends(ArcFollowCamera, _super);
  65116. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65117. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65118. _this.alpha = alpha;
  65119. _this.beta = beta;
  65120. _this.radius = radius;
  65121. _this.target = target;
  65122. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65123. _this.follow();
  65124. return _this;
  65125. }
  65126. ArcFollowCamera.prototype.follow = function () {
  65127. if (!this.target) {
  65128. return;
  65129. }
  65130. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65131. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65132. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65133. var targetPosition = this.target.getAbsolutePosition();
  65134. this.position = targetPosition.add(this._cartesianCoordinates);
  65135. this.setTarget(targetPosition);
  65136. };
  65137. ArcFollowCamera.prototype._checkInputs = function () {
  65138. _super.prototype._checkInputs.call(this);
  65139. this.follow();
  65140. };
  65141. ArcFollowCamera.prototype.getClassName = function () {
  65142. return "ArcFollowCamera";
  65143. };
  65144. return ArcFollowCamera;
  65145. }(BABYLON.TargetCamera));
  65146. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65147. })(BABYLON || (BABYLON = {}));
  65148. //# sourceMappingURL=babylon.followCamera.js.map
  65149. var BABYLON;
  65150. (function (BABYLON) {
  65151. // We're mainly based on the logic defined into the FreeCamera code
  65152. var UniversalCamera = /** @class */ (function (_super) {
  65153. __extends(UniversalCamera, _super);
  65154. //-- end properties for backward compatibility for inputs
  65155. function UniversalCamera(name, position, scene) {
  65156. var _this = _super.call(this, name, position, scene) || this;
  65157. _this.inputs.addGamepad();
  65158. return _this;
  65159. }
  65160. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65161. //-- Begin properties for backward compatibility for inputs
  65162. get: function () {
  65163. var gamepad = this.inputs.attached["gamepad"];
  65164. if (gamepad)
  65165. return gamepad.gamepadAngularSensibility;
  65166. return 0;
  65167. },
  65168. set: function (value) {
  65169. var gamepad = this.inputs.attached["gamepad"];
  65170. if (gamepad)
  65171. gamepad.gamepadAngularSensibility = value;
  65172. },
  65173. enumerable: true,
  65174. configurable: true
  65175. });
  65176. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65177. get: function () {
  65178. var gamepad = this.inputs.attached["gamepad"];
  65179. if (gamepad)
  65180. return gamepad.gamepadMoveSensibility;
  65181. return 0;
  65182. },
  65183. set: function (value) {
  65184. var gamepad = this.inputs.attached["gamepad"];
  65185. if (gamepad)
  65186. gamepad.gamepadMoveSensibility = value;
  65187. },
  65188. enumerable: true,
  65189. configurable: true
  65190. });
  65191. UniversalCamera.prototype.getClassName = function () {
  65192. return "UniversalCamera";
  65193. };
  65194. return UniversalCamera;
  65195. }(BABYLON.TouchCamera));
  65196. BABYLON.UniversalCamera = UniversalCamera;
  65197. })(BABYLON || (BABYLON = {}));
  65198. //# sourceMappingURL=babylon.universalCamera.js.map
  65199. var BABYLON;
  65200. (function (BABYLON) {
  65201. // We're mainly based on the logic defined into the FreeCamera code
  65202. var GamepadCamera = /** @class */ (function (_super) {
  65203. __extends(GamepadCamera, _super);
  65204. //-- end properties for backward compatibility for inputs
  65205. function GamepadCamera(name, position, scene) {
  65206. return _super.call(this, name, position, scene) || this;
  65207. }
  65208. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65209. //-- Begin properties for backward compatibility for inputs
  65210. get: function () {
  65211. var gamepad = this.inputs.attached["gamepad"];
  65212. if (gamepad)
  65213. return gamepad.gamepadAngularSensibility;
  65214. return 0;
  65215. },
  65216. set: function (value) {
  65217. var gamepad = this.inputs.attached["gamepad"];
  65218. if (gamepad)
  65219. gamepad.gamepadAngularSensibility = value;
  65220. },
  65221. enumerable: true,
  65222. configurable: true
  65223. });
  65224. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65225. get: function () {
  65226. var gamepad = this.inputs.attached["gamepad"];
  65227. if (gamepad)
  65228. return gamepad.gamepadMoveSensibility;
  65229. return 0;
  65230. },
  65231. set: function (value) {
  65232. var gamepad = this.inputs.attached["gamepad"];
  65233. if (gamepad)
  65234. gamepad.gamepadMoveSensibility = value;
  65235. },
  65236. enumerable: true,
  65237. configurable: true
  65238. });
  65239. GamepadCamera.prototype.getClassName = function () {
  65240. return "GamepadCamera";
  65241. };
  65242. return GamepadCamera;
  65243. }(BABYLON.UniversalCamera));
  65244. BABYLON.GamepadCamera = GamepadCamera;
  65245. })(BABYLON || (BABYLON = {}));
  65246. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65247. var BABYLON;
  65248. (function (BABYLON) {
  65249. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65250. function PostProcessRenderPipelineManager() {
  65251. this._renderPipelines = {};
  65252. }
  65253. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65254. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65255. };
  65256. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65257. if (unique === void 0) { unique = false; }
  65258. var renderPipeline = this._renderPipelines[renderPipelineName];
  65259. if (!renderPipeline) {
  65260. return;
  65261. }
  65262. renderPipeline._attachCameras(cameras, unique);
  65263. };
  65264. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65265. var renderPipeline = this._renderPipelines[renderPipelineName];
  65266. if (!renderPipeline) {
  65267. return;
  65268. }
  65269. renderPipeline._detachCameras(cameras);
  65270. };
  65271. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65272. var renderPipeline = this._renderPipelines[renderPipelineName];
  65273. if (!renderPipeline) {
  65274. return;
  65275. }
  65276. renderPipeline._enableEffect(renderEffectName, cameras);
  65277. };
  65278. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65279. var renderPipeline = this._renderPipelines[renderPipelineName];
  65280. if (!renderPipeline) {
  65281. return;
  65282. }
  65283. renderPipeline._disableEffect(renderEffectName, cameras);
  65284. };
  65285. PostProcessRenderPipelineManager.prototype.update = function () {
  65286. for (var renderPipelineName in this._renderPipelines) {
  65287. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65288. var pipeline = this._renderPipelines[renderPipelineName];
  65289. if (!pipeline.isSupported) {
  65290. pipeline.dispose();
  65291. delete this._renderPipelines[renderPipelineName];
  65292. }
  65293. else {
  65294. pipeline._update();
  65295. }
  65296. }
  65297. }
  65298. };
  65299. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65300. for (var renderPipelineName in this._renderPipelines) {
  65301. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65302. var pipeline = this._renderPipelines[renderPipelineName];
  65303. pipeline._rebuild();
  65304. }
  65305. }
  65306. };
  65307. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65308. for (var renderPipelineName in this._renderPipelines) {
  65309. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65310. var pipeline = this._renderPipelines[renderPipelineName];
  65311. pipeline.dispose();
  65312. }
  65313. }
  65314. };
  65315. return PostProcessRenderPipelineManager;
  65316. }());
  65317. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65318. })(BABYLON || (BABYLON = {}));
  65319. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65320. var BABYLON;
  65321. (function (BABYLON) {
  65322. /**
  65323. * This represents a set of one or more post processes in Babylon.
  65324. * A post process can be used to apply a shader to a texture after it is rendered.
  65325. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65326. */
  65327. var PostProcessRenderEffect = /** @class */ (function () {
  65328. /**
  65329. * Instantiates a post process render effect.
  65330. * A post process can be used to apply a shader to a texture after it is rendered.
  65331. * @param engine The engine the effect is tied to
  65332. * @param name The name of the effect
  65333. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65334. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65335. */
  65336. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65337. this._name = name;
  65338. this._singleInstance = singleInstance || true;
  65339. this._getPostProcesses = getPostProcesses;
  65340. this._cameras = {};
  65341. this._indicesForCamera = {};
  65342. this._postProcesses = {};
  65343. }
  65344. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65345. /**
  65346. * Checks if all the post processes in the effect are supported.
  65347. */
  65348. get: function () {
  65349. for (var index in this._postProcesses) {
  65350. for (var ppIndex in this._postProcesses[index]) {
  65351. if (!this._postProcesses[index][ppIndex].isSupported) {
  65352. return false;
  65353. }
  65354. }
  65355. }
  65356. return true;
  65357. },
  65358. enumerable: true,
  65359. configurable: true
  65360. });
  65361. /**
  65362. * Updates the current state of the effect
  65363. */
  65364. PostProcessRenderEffect.prototype._update = function () {
  65365. };
  65366. /**
  65367. * Attaches the effect on cameras
  65368. * @param cameras The camera to attach to.
  65369. */
  65370. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65371. var _this = this;
  65372. var cameraKey;
  65373. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65374. if (!cams) {
  65375. return;
  65376. }
  65377. for (var i = 0; i < cams.length; i++) {
  65378. var camera = cams[i];
  65379. var cameraName = camera.name;
  65380. if (this._singleInstance) {
  65381. cameraKey = 0;
  65382. }
  65383. else {
  65384. cameraKey = cameraName;
  65385. }
  65386. if (!this._postProcesses[cameraKey]) {
  65387. var postProcess = this._getPostProcesses();
  65388. if (postProcess) {
  65389. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65390. }
  65391. }
  65392. if (!this._indicesForCamera[cameraName]) {
  65393. this._indicesForCamera[cameraName] = [];
  65394. }
  65395. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65396. var index = camera.attachPostProcess(postProcess);
  65397. _this._indicesForCamera[cameraName].push(index);
  65398. });
  65399. if (!this._cameras[cameraName]) {
  65400. this._cameras[cameraName] = camera;
  65401. }
  65402. }
  65403. };
  65404. /**
  65405. * Detatches the effect on cameras
  65406. * @param cameras The camera to detatch from.
  65407. */
  65408. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65409. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65410. if (!cams) {
  65411. return;
  65412. }
  65413. for (var i = 0; i < cams.length; i++) {
  65414. var camera = cams[i];
  65415. var cameraName = camera.name;
  65416. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65417. camera.detachPostProcess(postProcess);
  65418. });
  65419. if (this._cameras[cameraName]) {
  65420. //this._indicesForCamera.splice(index, 1);
  65421. this._cameras[cameraName] = null;
  65422. }
  65423. }
  65424. };
  65425. /**
  65426. * Enables the effect on given cameras
  65427. * @param cameras The camera to enable.
  65428. */
  65429. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65430. var _this = this;
  65431. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65432. if (!cams) {
  65433. return;
  65434. }
  65435. for (var i = 0; i < cams.length; i++) {
  65436. var camera = cams[i];
  65437. var cameraName = camera.name;
  65438. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65439. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65440. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65441. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65442. });
  65443. }
  65444. }
  65445. }
  65446. };
  65447. /**
  65448. * Disables the effect on the given cameras
  65449. * @param cameras The camera to disable.
  65450. */
  65451. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65452. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65453. if (!cams) {
  65454. return;
  65455. }
  65456. for (var i = 0; i < cams.length; i++) {
  65457. var camera = cams[i];
  65458. var cameraName = camera.name;
  65459. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65460. camera.detachPostProcess(postProcess);
  65461. });
  65462. }
  65463. };
  65464. /**
  65465. * Gets a list of the post processes contained in the effect.
  65466. * @param camera The camera to get the post processes on.
  65467. * @returns The list of the post processes in the effect.
  65468. */
  65469. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65470. if (this._singleInstance) {
  65471. return this._postProcesses[0];
  65472. }
  65473. else {
  65474. if (!camera) {
  65475. return null;
  65476. }
  65477. return this._postProcesses[camera.name];
  65478. }
  65479. };
  65480. return PostProcessRenderEffect;
  65481. }());
  65482. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65483. })(BABYLON || (BABYLON = {}));
  65484. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65485. var BABYLON;
  65486. (function (BABYLON) {
  65487. var PostProcessRenderPipeline = /** @class */ (function () {
  65488. function PostProcessRenderPipeline(engine, name) {
  65489. this._name = name;
  65490. this._renderEffects = {};
  65491. this._renderEffectsForIsolatedPass = new Array();
  65492. this._cameras = [];
  65493. }
  65494. PostProcessRenderPipeline.prototype.getClassName = function () {
  65495. return "PostProcessRenderPipeline";
  65496. };
  65497. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65498. get: function () {
  65499. for (var renderEffectName in this._renderEffects) {
  65500. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65501. if (!this._renderEffects[renderEffectName].isSupported) {
  65502. return false;
  65503. }
  65504. }
  65505. }
  65506. return true;
  65507. },
  65508. enumerable: true,
  65509. configurable: true
  65510. });
  65511. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65512. this._renderEffects[renderEffect._name] = renderEffect;
  65513. };
  65514. // private
  65515. PostProcessRenderPipeline.prototype._rebuild = function () {
  65516. };
  65517. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65518. var renderEffects = this._renderEffects[renderEffectName];
  65519. if (!renderEffects) {
  65520. return;
  65521. }
  65522. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65523. };
  65524. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65525. var renderEffects = this._renderEffects[renderEffectName];
  65526. if (!renderEffects) {
  65527. return;
  65528. }
  65529. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65530. };
  65531. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65532. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65533. if (!cams) {
  65534. return;
  65535. }
  65536. var indicesToDelete = [];
  65537. var i;
  65538. for (i = 0; i < cams.length; i++) {
  65539. var camera = cams[i];
  65540. var cameraName = camera.name;
  65541. if (this._cameras.indexOf(camera) === -1) {
  65542. this._cameras[cameraName] = camera;
  65543. }
  65544. else if (unique) {
  65545. indicesToDelete.push(i);
  65546. }
  65547. }
  65548. for (i = 0; i < indicesToDelete.length; i++) {
  65549. cameras.splice(indicesToDelete[i], 1);
  65550. }
  65551. for (var renderEffectName in this._renderEffects) {
  65552. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65553. this._renderEffects[renderEffectName]._attachCameras(cams);
  65554. }
  65555. }
  65556. };
  65557. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65558. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65559. if (!cams) {
  65560. return;
  65561. }
  65562. for (var renderEffectName in this._renderEffects) {
  65563. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65564. this._renderEffects[renderEffectName]._detachCameras(cams);
  65565. }
  65566. }
  65567. for (var i = 0; i < cams.length; i++) {
  65568. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65569. }
  65570. };
  65571. PostProcessRenderPipeline.prototype._update = function () {
  65572. for (var renderEffectName in this._renderEffects) {
  65573. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65574. this._renderEffects[renderEffectName]._update();
  65575. }
  65576. }
  65577. for (var i = 0; i < this._cameras.length; i++) {
  65578. var cameraName = this._cameras[i].name;
  65579. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65580. this._renderEffectsForIsolatedPass[cameraName]._update();
  65581. }
  65582. }
  65583. };
  65584. PostProcessRenderPipeline.prototype._reset = function () {
  65585. this._renderEffects = {};
  65586. this._renderEffectsForIsolatedPass = new Array();
  65587. };
  65588. PostProcessRenderPipeline.prototype.dispose = function () {
  65589. // Must be implemented by children
  65590. };
  65591. __decorate([
  65592. BABYLON.serialize()
  65593. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65594. return PostProcessRenderPipeline;
  65595. }());
  65596. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65597. })(BABYLON || (BABYLON = {}));
  65598. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65599. var BABYLON;
  65600. (function (BABYLON) {
  65601. /**
  65602. * This represents a depth renderer in Babylon.
  65603. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65604. */
  65605. var DepthRenderer = /** @class */ (function () {
  65606. /**
  65607. * Instantiates a depth renderer
  65608. * @param scene The scene the renderer belongs to
  65609. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65610. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65611. */
  65612. function DepthRenderer(scene, type, camera) {
  65613. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65614. if (camera === void 0) { camera = null; }
  65615. var _this = this;
  65616. this._scene = scene;
  65617. this._camera = camera;
  65618. var engine = scene.getEngine();
  65619. // Render target
  65620. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65621. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65622. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65623. this._depthMap.refreshRate = 1;
  65624. this._depthMap.renderParticles = false;
  65625. this._depthMap.renderList = null;
  65626. // Camera to get depth map from to support multiple concurrent cameras
  65627. this._depthMap.activeCamera = this._camera;
  65628. this._depthMap.ignoreCameraViewport = true;
  65629. this._depthMap.useCameraPostProcesses = false;
  65630. // set default depth value to 1.0 (far away)
  65631. this._depthMap.onClearObservable.add(function (engine) {
  65632. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65633. });
  65634. // Custom render function
  65635. var renderSubMesh = function (subMesh) {
  65636. var mesh = subMesh.getRenderingMesh();
  65637. var scene = _this._scene;
  65638. var engine = scene.getEngine();
  65639. var material = subMesh.getMaterial();
  65640. if (!material) {
  65641. return;
  65642. }
  65643. // Culling and reverse (right handed system)
  65644. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65645. // Managing instances
  65646. var batch = mesh._getInstancesRenderList(subMesh._id);
  65647. if (batch.mustReturn) {
  65648. return;
  65649. }
  65650. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65651. var camera = _this._camera || scene.activeCamera;
  65652. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65653. engine.enableEffect(_this._effect);
  65654. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65655. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65656. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65657. // Alpha test
  65658. if (material && material.needAlphaTesting()) {
  65659. var alphaTexture = material.getAlphaTestTexture();
  65660. if (alphaTexture) {
  65661. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65662. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65663. }
  65664. }
  65665. // Bones
  65666. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65667. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65668. }
  65669. // Draw
  65670. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65671. }
  65672. };
  65673. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65674. var index;
  65675. if (depthOnlySubMeshes.length) {
  65676. engine.setColorWrite(false);
  65677. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65678. renderSubMesh(depthOnlySubMeshes.data[index]);
  65679. }
  65680. engine.setColorWrite(true);
  65681. }
  65682. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65683. renderSubMesh(opaqueSubMeshes.data[index]);
  65684. }
  65685. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65686. renderSubMesh(alphaTestSubMeshes.data[index]);
  65687. }
  65688. };
  65689. }
  65690. /**
  65691. * Creates the depth rendering effect and checks if the effect is ready.
  65692. * @param subMesh The submesh to be used to render the depth map of
  65693. * @param useInstances If multiple world instances should be used
  65694. * @returns if the depth renderer is ready to render the depth map
  65695. */
  65696. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65697. var material = subMesh.getMaterial();
  65698. if (material.disableDepthWrite) {
  65699. return false;
  65700. }
  65701. var defines = [];
  65702. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65703. var mesh = subMesh.getMesh();
  65704. // Alpha test
  65705. if (material && material.needAlphaTesting()) {
  65706. defines.push("#define ALPHATEST");
  65707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65708. attribs.push(BABYLON.VertexBuffer.UVKind);
  65709. defines.push("#define UV1");
  65710. }
  65711. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65712. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65713. defines.push("#define UV2");
  65714. }
  65715. }
  65716. // Bones
  65717. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65720. if (mesh.numBoneInfluencers > 4) {
  65721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65723. }
  65724. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65725. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65726. }
  65727. else {
  65728. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65729. }
  65730. // Instances
  65731. if (useInstances) {
  65732. defines.push("#define INSTANCES");
  65733. attribs.push("world0");
  65734. attribs.push("world1");
  65735. attribs.push("world2");
  65736. attribs.push("world3");
  65737. }
  65738. // Get correct effect
  65739. var join = defines.join("\n");
  65740. if (this._cachedDefines !== join) {
  65741. this._cachedDefines = join;
  65742. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65743. }
  65744. return this._effect.isReady();
  65745. };
  65746. /**
  65747. * Gets the texture which the depth map will be written to.
  65748. * @returns The depth map texture
  65749. */
  65750. DepthRenderer.prototype.getDepthMap = function () {
  65751. return this._depthMap;
  65752. };
  65753. /**
  65754. * Disposes of the depth renderer.
  65755. */
  65756. DepthRenderer.prototype.dispose = function () {
  65757. this._depthMap.dispose();
  65758. };
  65759. return DepthRenderer;
  65760. }());
  65761. BABYLON.DepthRenderer = DepthRenderer;
  65762. })(BABYLON || (BABYLON = {}));
  65763. //# sourceMappingURL=babylon.depthRenderer.js.map
  65764. var BABYLON;
  65765. (function (BABYLON) {
  65766. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65767. __extends(SSAORenderingPipeline, _super);
  65768. /**
  65769. * @constructor
  65770. * @param {string} name - The rendering pipeline name
  65771. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65772. * @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 }
  65773. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65774. */
  65775. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65776. var _this = _super.call(this, scene.getEngine(), name) || this;
  65777. // Members
  65778. /**
  65779. * The PassPostProcess id in the pipeline that contains the original scene color
  65780. * @type {string}
  65781. */
  65782. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65783. /**
  65784. * The SSAO PostProcess id in the pipeline
  65785. * @type {string}
  65786. */
  65787. _this.SSAORenderEffect = "SSAORenderEffect";
  65788. /**
  65789. * The horizontal blur PostProcess id in the pipeline
  65790. * @type {string}
  65791. */
  65792. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65793. /**
  65794. * The vertical blur PostProcess id in the pipeline
  65795. * @type {string}
  65796. */
  65797. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65798. /**
  65799. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65800. * @type {string}
  65801. */
  65802. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65803. /**
  65804. * The output strength of the SSAO post-process. Default value is 1.0.
  65805. * @type {number}
  65806. */
  65807. _this.totalStrength = 1.0;
  65808. /**
  65809. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65810. * @type {number}
  65811. */
  65812. _this.radius = 0.0001;
  65813. /**
  65814. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65815. * Must not be equal to fallOff and superior to fallOff.
  65816. * Default value is 0.975
  65817. * @type {number}
  65818. */
  65819. _this.area = 0.0075;
  65820. /**
  65821. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65822. * Must not be equal to area and inferior to area.
  65823. * Default value is 0.0
  65824. * @type {number}
  65825. */
  65826. _this.fallOff = 0.000001;
  65827. /**
  65828. * The base color of the SSAO post-process
  65829. * The final result is "base + ssao" between [0, 1]
  65830. * @type {number}
  65831. */
  65832. _this.base = 0.5;
  65833. _this._firstUpdate = true;
  65834. _this._scene = scene;
  65835. // Set up assets
  65836. _this._createRandomTexture();
  65837. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65838. var ssaoRatio = ratio.ssaoRatio || ratio;
  65839. var combineRatio = ratio.combineRatio || ratio;
  65840. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65841. _this._createSSAOPostProcess(ssaoRatio);
  65842. _this._createBlurPostProcess(ssaoRatio);
  65843. _this._createSSAOCombinePostProcess(combineRatio);
  65844. // Set up pipeline
  65845. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65846. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65847. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65848. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65849. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65850. // Finish
  65851. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65852. if (cameras)
  65853. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65854. return _this;
  65855. }
  65856. // Public Methods
  65857. /**
  65858. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65859. */
  65860. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65861. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65862. for (var i = 0; i < this._scene.cameras.length; i++) {
  65863. var camera = this._scene.cameras[i];
  65864. this._originalColorPostProcess.dispose(camera);
  65865. this._ssaoPostProcess.dispose(camera);
  65866. this._blurHPostProcess.dispose(camera);
  65867. this._blurVPostProcess.dispose(camera);
  65868. this._ssaoCombinePostProcess.dispose(camera);
  65869. }
  65870. this._randomTexture.dispose();
  65871. if (disableDepthRender)
  65872. this._scene.disableDepthRenderer();
  65873. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65874. _super.prototype.dispose.call(this);
  65875. };
  65876. // Private Methods
  65877. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65878. var _this = this;
  65879. var size = 16;
  65880. 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);
  65881. 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);
  65882. this._blurHPostProcess.onActivateObservable.add(function () {
  65883. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65884. _this._blurHPostProcess.kernel = size * dw;
  65885. });
  65886. this._blurVPostProcess.onActivateObservable.add(function () {
  65887. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65888. _this._blurVPostProcess.kernel = size * dw;
  65889. });
  65890. };
  65891. SSAORenderingPipeline.prototype._rebuild = function () {
  65892. this._firstUpdate = true;
  65893. _super.prototype._rebuild.call(this);
  65894. };
  65895. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65896. var _this = this;
  65897. var numSamples = 16;
  65898. var sampleSphere = [
  65899. 0.5381, 0.1856, -0.4319,
  65900. 0.1379, 0.2486, 0.4430,
  65901. 0.3371, 0.5679, -0.0057,
  65902. -0.6999, -0.0451, -0.0019,
  65903. 0.0689, -0.1598, -0.8547,
  65904. 0.0560, 0.0069, -0.1843,
  65905. -0.0146, 0.1402, 0.0762,
  65906. 0.0100, -0.1924, -0.0344,
  65907. -0.3577, -0.5301, -0.4358,
  65908. -0.3169, 0.1063, 0.0158,
  65909. 0.0103, -0.5869, 0.0046,
  65910. -0.0897, -0.4940, 0.3287,
  65911. 0.7119, -0.0154, -0.0918,
  65912. -0.0533, 0.0596, -0.5411,
  65913. 0.0352, -0.0631, 0.5460,
  65914. -0.4776, 0.2847, -0.0271
  65915. ];
  65916. var samplesFactor = 1.0 / numSamples;
  65917. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65918. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65919. "area", "fallOff", "base", "range", "viewport"
  65920. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65921. this._ssaoPostProcess.onApply = function (effect) {
  65922. if (_this._firstUpdate) {
  65923. effect.setArray3("sampleSphere", sampleSphere);
  65924. effect.setFloat("samplesFactor", samplesFactor);
  65925. effect.setFloat("randTextureTiles", 4.0);
  65926. }
  65927. effect.setFloat("totalStrength", _this.totalStrength);
  65928. effect.setFloat("radius", _this.radius);
  65929. effect.setFloat("area", _this.area);
  65930. effect.setFloat("fallOff", _this.fallOff);
  65931. effect.setFloat("base", _this.base);
  65932. effect.setTexture("textureSampler", _this._depthTexture);
  65933. effect.setTexture("randomSampler", _this._randomTexture);
  65934. };
  65935. };
  65936. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65937. var _this = this;
  65938. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65939. this._ssaoCombinePostProcess.onApply = function (effect) {
  65940. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65941. };
  65942. };
  65943. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65944. var size = 512;
  65945. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65946. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65947. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65948. var context = this._randomTexture.getContext();
  65949. var rand = function (min, max) {
  65950. return Math.random() * (max - min) + min;
  65951. };
  65952. var randVector = BABYLON.Vector3.Zero();
  65953. for (var x = 0; x < size; x++) {
  65954. for (var y = 0; y < size; y++) {
  65955. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65956. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65957. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65958. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65959. context.fillRect(x, y, 1, 1);
  65960. }
  65961. }
  65962. this._randomTexture.update(false);
  65963. };
  65964. __decorate([
  65965. BABYLON.serialize()
  65966. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65967. __decorate([
  65968. BABYLON.serialize()
  65969. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65970. __decorate([
  65971. BABYLON.serialize()
  65972. ], SSAORenderingPipeline.prototype, "area", void 0);
  65973. __decorate([
  65974. BABYLON.serialize()
  65975. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65976. __decorate([
  65977. BABYLON.serialize()
  65978. ], SSAORenderingPipeline.prototype, "base", void 0);
  65979. return SSAORenderingPipeline;
  65980. }(BABYLON.PostProcessRenderPipeline));
  65981. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65982. })(BABYLON || (BABYLON = {}));
  65983. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65984. var BABYLON;
  65985. (function (BABYLON) {
  65986. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65987. __extends(SSAO2RenderingPipeline, _super);
  65988. /**
  65989. * @constructor
  65990. * @param {string} name - The rendering pipeline name
  65991. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65992. * @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 }
  65993. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65994. */
  65995. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65996. var _this = _super.call(this, scene.getEngine(), name) || this;
  65997. // Members
  65998. /**
  65999. * The PassPostProcess id in the pipeline that contains the original scene color
  66000. * @type {string}
  66001. */
  66002. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66003. /**
  66004. * The SSAO PostProcess id in the pipeline
  66005. * @type {string}
  66006. */
  66007. _this.SSAORenderEffect = "SSAORenderEffect";
  66008. /**
  66009. * The horizontal blur PostProcess id in the pipeline
  66010. * @type {string}
  66011. */
  66012. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66013. /**
  66014. * The vertical blur PostProcess id in the pipeline
  66015. * @type {string}
  66016. */
  66017. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66018. /**
  66019. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66020. * @type {string}
  66021. */
  66022. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66023. /**
  66024. * The output strength of the SSAO post-process. Default value is 1.0.
  66025. * @type {number}
  66026. */
  66027. _this.totalStrength = 1.0;
  66028. /**
  66029. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66030. * @type {number}
  66031. */
  66032. _this.maxZ = 100.0;
  66033. /**
  66034. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66035. * @type {number}
  66036. */
  66037. _this.minZAspect = 0.2;
  66038. /**
  66039. * Number of samples used for the SSAO calculations. Default value is 8
  66040. * @type {number}
  66041. */
  66042. _this._samples = 8;
  66043. /**
  66044. * Are we using bilateral blur ?
  66045. * @type {boolean}
  66046. */
  66047. _this._expensiveBlur = true;
  66048. /**
  66049. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66050. * @type {number}
  66051. */
  66052. _this.radius = 2.0;
  66053. /**
  66054. * The base color of the SSAO post-process
  66055. * The final result is "base + ssao" between [0, 1]
  66056. * @type {number}
  66057. */
  66058. _this.base = 0.1;
  66059. _this._firstUpdate = true;
  66060. _this._scene = scene;
  66061. if (!_this.isSupported) {
  66062. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66063. return _this;
  66064. }
  66065. var ssaoRatio = ratio.ssaoRatio || ratio;
  66066. var blurRatio = ratio.blurRatio || ratio;
  66067. // Set up assets
  66068. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66069. _this._createRandomTexture();
  66070. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66071. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66072. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66073. _this._createSSAOPostProcess(1.0);
  66074. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66075. _this._createSSAOCombinePostProcess(blurRatio);
  66076. // Set up pipeline
  66077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66082. // Finish
  66083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66084. if (cameras)
  66085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66086. return _this;
  66087. }
  66088. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66089. get: function () {
  66090. return this._samples;
  66091. },
  66092. set: function (n) {
  66093. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66094. this._samples = n;
  66095. this._sampleSphere = this._generateHemisphere();
  66096. this._firstUpdate = true;
  66097. },
  66098. enumerable: true,
  66099. configurable: true
  66100. });
  66101. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66102. get: function () {
  66103. return this._expensiveBlur;
  66104. },
  66105. set: function (b) {
  66106. 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"]);
  66107. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66108. this._expensiveBlur = b;
  66109. this._firstUpdate = true;
  66110. },
  66111. enumerable: true,
  66112. configurable: true
  66113. });
  66114. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66115. /**
  66116. * Support test.
  66117. * @type {boolean}
  66118. */
  66119. get: function () {
  66120. var engine = BABYLON.Engine.LastCreatedEngine;
  66121. if (!engine) {
  66122. return false;
  66123. }
  66124. return engine.getCaps().drawBuffersExtension;
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. // Public Methods
  66130. /**
  66131. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66132. */
  66133. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66134. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66135. for (var i = 0; i < this._scene.cameras.length; i++) {
  66136. var camera = this._scene.cameras[i];
  66137. this._originalColorPostProcess.dispose(camera);
  66138. this._ssaoPostProcess.dispose(camera);
  66139. this._blurHPostProcess.dispose(camera);
  66140. this._blurVPostProcess.dispose(camera);
  66141. this._ssaoCombinePostProcess.dispose(camera);
  66142. }
  66143. this._randomTexture.dispose();
  66144. if (disableGeometryBufferRenderer)
  66145. this._scene.disableGeometryBufferRenderer();
  66146. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66147. _super.prototype.dispose.call(this);
  66148. };
  66149. // Private Methods
  66150. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66151. var _this = this;
  66152. this._samplerOffsets = [];
  66153. var expensive = this.expensiveBlur;
  66154. for (var i = -8; i < 8; i++) {
  66155. this._samplerOffsets.push(i * 2 + 0.5);
  66156. }
  66157. 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");
  66158. this._blurHPostProcess.onApply = function (effect) {
  66159. if (!_this._scene.activeCamera) {
  66160. return;
  66161. }
  66162. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66163. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66164. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66165. effect.setFloat("radius", _this.radius);
  66166. effect.setTexture("depthSampler", _this._depthTexture);
  66167. if (_this._firstUpdate) {
  66168. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66169. }
  66170. };
  66171. 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");
  66172. this._blurVPostProcess.onApply = function (effect) {
  66173. if (!_this._scene.activeCamera) {
  66174. return;
  66175. }
  66176. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66177. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66178. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66179. effect.setFloat("radius", _this.radius);
  66180. effect.setTexture("depthSampler", _this._depthTexture);
  66181. if (_this._firstUpdate) {
  66182. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66183. _this._firstUpdate = false;
  66184. }
  66185. };
  66186. };
  66187. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66188. this._firstUpdate = true;
  66189. _super.prototype._rebuild.call(this);
  66190. };
  66191. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66192. var numSamples = this.samples;
  66193. var result = [];
  66194. var vector, scale;
  66195. var rand = function (min, max) {
  66196. return Math.random() * (max - min) + min;
  66197. };
  66198. var i = 0;
  66199. while (i < numSamples) {
  66200. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66201. vector.normalize();
  66202. scale = i / numSamples;
  66203. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66204. vector.scaleInPlace(scale);
  66205. result.push(vector.x, vector.y, vector.z);
  66206. i++;
  66207. }
  66208. return result;
  66209. };
  66210. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66211. var _this = this;
  66212. var numSamples = this.samples;
  66213. this._sampleSphere = this._generateHemisphere();
  66214. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66215. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66216. "base", "range", "projection", "near", "far", "texelSize",
  66217. "xViewport", "yViewport", "maxZ", "minZAspect"
  66218. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66219. this._ssaoPostProcess.onApply = function (effect) {
  66220. if (_this._firstUpdate) {
  66221. effect.setArray3("sampleSphere", _this._sampleSphere);
  66222. effect.setFloat("randTextureTiles", 4.0);
  66223. }
  66224. if (!_this._scene.activeCamera) {
  66225. return;
  66226. }
  66227. effect.setFloat("samplesFactor", 1 / _this.samples);
  66228. effect.setFloat("totalStrength", _this.totalStrength);
  66229. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66230. effect.setFloat("radius", _this.radius);
  66231. effect.setFloat("maxZ", _this.maxZ);
  66232. effect.setFloat("minZAspect", _this.minZAspect);
  66233. effect.setFloat("base", _this.base);
  66234. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66235. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66236. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66237. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66238. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66239. effect.setTexture("textureSampler", _this._depthTexture);
  66240. effect.setTexture("normalSampler", _this._normalTexture);
  66241. effect.setTexture("randomSampler", _this._randomTexture);
  66242. };
  66243. };
  66244. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66245. var _this = this;
  66246. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66247. this._ssaoCombinePostProcess.onApply = function (effect) {
  66248. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66249. };
  66250. };
  66251. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66252. var size = 512;
  66253. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66254. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66255. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66256. var context = this._randomTexture.getContext();
  66257. var rand = function (min, max) {
  66258. return Math.random() * (max - min) + min;
  66259. };
  66260. var randVector = BABYLON.Vector3.Zero();
  66261. for (var x = 0; x < size; x++) {
  66262. for (var y = 0; y < size; y++) {
  66263. randVector.x = rand(0.0, 1.0);
  66264. randVector.y = rand(0.0, 1.0);
  66265. randVector.z = 0.0;
  66266. randVector.normalize();
  66267. randVector.scaleInPlace(255);
  66268. randVector.x = Math.floor(randVector.x);
  66269. randVector.y = Math.floor(randVector.y);
  66270. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66271. context.fillRect(x, y, 1, 1);
  66272. }
  66273. }
  66274. this._randomTexture.update(false);
  66275. };
  66276. __decorate([
  66277. BABYLON.serialize()
  66278. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66279. __decorate([
  66280. BABYLON.serialize()
  66281. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66282. __decorate([
  66283. BABYLON.serialize()
  66284. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66285. __decorate([
  66286. BABYLON.serialize("samples")
  66287. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66288. __decorate([
  66289. BABYLON.serialize("expensiveBlur")
  66290. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66291. __decorate([
  66292. BABYLON.serialize()
  66293. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66294. __decorate([
  66295. BABYLON.serialize()
  66296. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66297. return SSAO2RenderingPipeline;
  66298. }(BABYLON.PostProcessRenderPipeline));
  66299. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66300. })(BABYLON || (BABYLON = {}));
  66301. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66302. // BABYLON.JS Chromatic Aberration GLSL Shader
  66303. // Author: Olivier Guyot
  66304. // Separates very slightly R, G and B colors on the edges of the screen
  66305. // Inspired by Francois Tarlier & Martins Upitis
  66306. var BABYLON;
  66307. (function (BABYLON) {
  66308. var LensRenderingPipeline = /** @class */ (function (_super) {
  66309. __extends(LensRenderingPipeline, _super);
  66310. /**
  66311. * @constructor
  66312. *
  66313. * Effect parameters are as follow:
  66314. * {
  66315. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66316. * edge_blur: number; // from 0 to x (1 for realism)
  66317. * distortion: number; // from 0 to x (1 for realism)
  66318. * grain_amount: number; // from 0 to 1
  66319. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66320. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66321. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66322. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66323. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66324. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66325. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66326. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66327. * }
  66328. * Note: if an effect parameter is unset, effect is disabled
  66329. *
  66330. * @param {string} name - The rendering pipeline name
  66331. * @param {object} parameters - An object containing all parameters (see above)
  66332. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66333. * @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)
  66334. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66335. */
  66336. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66337. if (ratio === void 0) { ratio = 1.0; }
  66338. var _this = _super.call(this, scene.getEngine(), name) || this;
  66339. // Lens effects can be of the following:
  66340. // - chromatic aberration (slight shift of RGB colors)
  66341. // - blur on the edge of the lens
  66342. // - lens distortion
  66343. // - depth-of-field blur & highlights enhancing
  66344. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66345. // - grain effect (noise or custom texture)
  66346. // Two additional texture samplers are needed:
  66347. // - depth map (for depth-of-field)
  66348. // - grain texture
  66349. /**
  66350. * The chromatic aberration PostProcess id in the pipeline
  66351. * @type {string}
  66352. */
  66353. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66354. /**
  66355. * The highlights enhancing PostProcess id in the pipeline
  66356. * @type {string}
  66357. */
  66358. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66359. /**
  66360. * The depth-of-field PostProcess id in the pipeline
  66361. * @type {string}
  66362. */
  66363. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66364. _this._scene = scene;
  66365. // Fetch texture samplers
  66366. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66367. if (parameters.grain_texture) {
  66368. _this._grainTexture = parameters.grain_texture;
  66369. }
  66370. else {
  66371. _this._createGrainTexture();
  66372. }
  66373. // save parameters
  66374. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66375. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66376. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66377. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66378. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66379. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66380. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66381. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66382. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66383. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66384. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66385. // Create effects
  66386. _this._createChromaticAberrationPostProcess(ratio);
  66387. _this._createHighlightsPostProcess(ratio);
  66388. _this._createDepthOfFieldPostProcess(ratio / 4);
  66389. // Set up pipeline
  66390. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66391. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66392. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66393. if (_this._highlightsGain === -1) {
  66394. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66395. }
  66396. // Finish
  66397. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66398. if (cameras) {
  66399. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66400. }
  66401. return _this;
  66402. }
  66403. // public methods (self explanatory)
  66404. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66405. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66406. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66407. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66408. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66409. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66410. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66411. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66412. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66413. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66414. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66415. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66416. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66417. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66418. };
  66419. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66420. this._highlightsPostProcess.updateEffect();
  66421. };
  66422. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66423. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66424. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66425. this._highlightsGain = amount;
  66426. };
  66427. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66428. if (this._highlightsGain === -1) {
  66429. this._highlightsGain = 1.0;
  66430. }
  66431. this._highlightsThreshold = amount;
  66432. };
  66433. LensRenderingPipeline.prototype.disableHighlights = function () {
  66434. this._highlightsGain = -1;
  66435. };
  66436. /**
  66437. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66438. */
  66439. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66440. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66441. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66442. this._chromaticAberrationPostProcess = null;
  66443. this._highlightsPostProcess = null;
  66444. this._depthOfFieldPostProcess = null;
  66445. this._grainTexture.dispose();
  66446. if (disableDepthRender)
  66447. this._scene.disableDepthRenderer();
  66448. };
  66449. // colors shifting and distortion
  66450. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66451. var _this = this;
  66452. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66453. [], // samplers
  66454. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66455. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66456. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66457. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66458. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66459. };
  66460. };
  66461. // highlights enhancing
  66462. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66463. var _this = this;
  66464. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66465. [], // samplers
  66466. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66467. this._highlightsPostProcess.onApply = function (effect) {
  66468. effect.setFloat('gain', _this._highlightsGain);
  66469. effect.setFloat('threshold', _this._highlightsThreshold);
  66470. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66471. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66472. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66473. };
  66474. };
  66475. // colors shifting and distortion
  66476. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66477. var _this = this;
  66478. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66479. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66480. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66481. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66482. this._depthOfFieldPostProcess.onApply = function (effect) {
  66483. effect.setTexture("depthSampler", _this._depthTexture);
  66484. effect.setTexture("grainSampler", _this._grainTexture);
  66485. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66486. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66487. effect.setFloat('grain_amount', _this._grainAmount);
  66488. effect.setBool('blur_noise', _this._blurNoise);
  66489. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66490. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66491. effect.setFloat('distortion', _this._distortion);
  66492. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66493. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66494. effect.setFloat('aperture', _this._dofAperture);
  66495. effect.setFloat('darken', _this._dofDarken);
  66496. effect.setFloat('edge_blur', _this._edgeBlur);
  66497. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66498. if (_this._scene.activeCamera) {
  66499. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66500. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66501. }
  66502. };
  66503. };
  66504. // creates a black and white random noise texture, 512x512
  66505. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66506. var size = 512;
  66507. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66508. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66509. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66510. var context = this._grainTexture.getContext();
  66511. var rand = function (min, max) {
  66512. return Math.random() * (max - min) + min;
  66513. };
  66514. var value;
  66515. for (var x = 0; x < size; x++) {
  66516. for (var y = 0; y < size; y++) {
  66517. value = Math.floor(rand(0.42, 0.58) * 255);
  66518. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66519. context.fillRect(x, y, 1, 1);
  66520. }
  66521. }
  66522. this._grainTexture.update(false);
  66523. };
  66524. return LensRenderingPipeline;
  66525. }(BABYLON.PostProcessRenderPipeline));
  66526. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66527. })(BABYLON || (BABYLON = {}));
  66528. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66529. var BABYLON;
  66530. (function (BABYLON) {
  66531. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66532. __extends(StandardRenderingPipeline, _super);
  66533. /**
  66534. * @constructor
  66535. * @param {string} name - The rendering pipeline name
  66536. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66537. * @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)
  66538. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66539. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66540. */
  66541. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66542. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66543. var _this = _super.call(this, scene.getEngine(), name) || this;
  66544. _this.downSampleX4PostProcess = null;
  66545. _this.brightPassPostProcess = null;
  66546. _this.blurHPostProcesses = [];
  66547. _this.blurVPostProcesses = [];
  66548. _this.textureAdderPostProcess = null;
  66549. _this.volumetricLightPostProcess = null;
  66550. _this.volumetricLightSmoothXPostProcess = null;
  66551. _this.volumetricLightSmoothYPostProcess = null;
  66552. _this.volumetricLightMergePostProces = null;
  66553. _this.volumetricLightFinalPostProcess = null;
  66554. _this.luminancePostProcess = null;
  66555. _this.luminanceDownSamplePostProcesses = [];
  66556. _this.hdrPostProcess = null;
  66557. _this.textureAdderFinalPostProcess = null;
  66558. _this.lensFlareFinalPostProcess = null;
  66559. _this.hdrFinalPostProcess = null;
  66560. _this.lensFlarePostProcess = null;
  66561. _this.lensFlareComposePostProcess = null;
  66562. _this.motionBlurPostProcess = null;
  66563. _this.depthOfFieldPostProcess = null;
  66564. // Values
  66565. _this.brightThreshold = 1.0;
  66566. _this.blurWidth = 512.0;
  66567. _this.horizontalBlur = false;
  66568. _this.exposure = 1.0;
  66569. _this.lensTexture = null;
  66570. _this.volumetricLightCoefficient = 0.2;
  66571. _this.volumetricLightPower = 4.0;
  66572. _this.volumetricLightBlurScale = 64.0;
  66573. _this.sourceLight = null;
  66574. _this.hdrMinimumLuminance = 1.0;
  66575. _this.hdrDecreaseRate = 0.5;
  66576. _this.hdrIncreaseRate = 0.5;
  66577. _this.lensColorTexture = null;
  66578. _this.lensFlareStrength = 20.0;
  66579. _this.lensFlareGhostDispersal = 1.4;
  66580. _this.lensFlareHaloWidth = 0.7;
  66581. _this.lensFlareDistortionStrength = 16.0;
  66582. _this.lensStarTexture = null;
  66583. _this.lensFlareDirtTexture = null;
  66584. _this.depthOfFieldDistance = 10.0;
  66585. _this.depthOfFieldBlurWidth = 64.0;
  66586. _this.motionStrength = 1.0;
  66587. // IAnimatable
  66588. _this.animations = [];
  66589. _this._currentDepthOfFieldSource = null;
  66590. _this._hdrCurrentLuminance = 1.0;
  66591. // Getters and setters
  66592. _this._bloomEnabled = true;
  66593. _this._depthOfFieldEnabled = false;
  66594. _this._vlsEnabled = false;
  66595. _this._lensFlareEnabled = false;
  66596. _this._hdrEnabled = false;
  66597. _this._motionBlurEnabled = false;
  66598. _this._motionBlurSamples = 64.0;
  66599. _this._volumetricLightStepsCount = 50.0;
  66600. _this._cameras = cameras || [];
  66601. // Initialize
  66602. _this._scene = scene;
  66603. _this._basePostProcess = originalPostProcess;
  66604. _this._ratio = ratio;
  66605. // Misc
  66606. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66607. // Finish
  66608. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66609. _this._buildPipeline();
  66610. return _this;
  66611. }
  66612. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66613. get: function () {
  66614. return this._bloomEnabled;
  66615. },
  66616. set: function (enabled) {
  66617. if (this._bloomEnabled === enabled) {
  66618. return;
  66619. }
  66620. this._bloomEnabled = enabled;
  66621. this._buildPipeline();
  66622. },
  66623. enumerable: true,
  66624. configurable: true
  66625. });
  66626. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66627. get: function () {
  66628. return this._depthOfFieldEnabled;
  66629. },
  66630. set: function (enabled) {
  66631. if (this._depthOfFieldEnabled === enabled) {
  66632. return;
  66633. }
  66634. this._depthOfFieldEnabled = enabled;
  66635. this._buildPipeline();
  66636. },
  66637. enumerable: true,
  66638. configurable: true
  66639. });
  66640. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66641. get: function () {
  66642. return this._lensFlareEnabled;
  66643. },
  66644. set: function (enabled) {
  66645. if (this._lensFlareEnabled === enabled) {
  66646. return;
  66647. }
  66648. this._lensFlareEnabled = enabled;
  66649. this._buildPipeline();
  66650. },
  66651. enumerable: true,
  66652. configurable: true
  66653. });
  66654. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66655. get: function () {
  66656. return this._hdrEnabled;
  66657. },
  66658. set: function (enabled) {
  66659. if (this._hdrEnabled === enabled) {
  66660. return;
  66661. }
  66662. this._hdrEnabled = enabled;
  66663. this._buildPipeline();
  66664. },
  66665. enumerable: true,
  66666. configurable: true
  66667. });
  66668. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66669. get: function () {
  66670. return this._vlsEnabled;
  66671. },
  66672. set: function (enabled) {
  66673. if (this._vlsEnabled === enabled) {
  66674. return;
  66675. }
  66676. if (enabled) {
  66677. var geometry = this._scene.enableGeometryBufferRenderer();
  66678. if (!geometry) {
  66679. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66680. return;
  66681. }
  66682. }
  66683. this._vlsEnabled = enabled;
  66684. this._buildPipeline();
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66690. get: function () {
  66691. return this._motionBlurEnabled;
  66692. },
  66693. set: function (enabled) {
  66694. if (this._motionBlurEnabled === enabled) {
  66695. return;
  66696. }
  66697. this._motionBlurEnabled = enabled;
  66698. this._buildPipeline();
  66699. },
  66700. enumerable: true,
  66701. configurable: true
  66702. });
  66703. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66704. get: function () {
  66705. return this._volumetricLightStepsCount;
  66706. },
  66707. set: function (count) {
  66708. if (this.volumetricLightPostProcess) {
  66709. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66710. }
  66711. this._volumetricLightStepsCount = count;
  66712. },
  66713. enumerable: true,
  66714. configurable: true
  66715. });
  66716. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66717. get: function () {
  66718. return this._motionBlurSamples;
  66719. },
  66720. set: function (samples) {
  66721. if (this.motionBlurPostProcess) {
  66722. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66723. }
  66724. this._motionBlurSamples = samples;
  66725. },
  66726. enumerable: true,
  66727. configurable: true
  66728. });
  66729. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66730. var _this = this;
  66731. var ratio = this._ratio;
  66732. var scene = this._scene;
  66733. this._disposePostProcesses();
  66734. this._reset();
  66735. // Create pass post-process
  66736. if (!this._basePostProcess) {
  66737. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66738. this.originalPostProcess.onApply = function (effect) {
  66739. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66740. };
  66741. }
  66742. else {
  66743. this.originalPostProcess = this._basePostProcess;
  66744. }
  66745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66746. this._currentDepthOfFieldSource = this.originalPostProcess;
  66747. if (this._vlsEnabled) {
  66748. // Create volumetric light
  66749. this._createVolumetricLightPostProcess(scene, ratio);
  66750. // Create volumetric light final post-process
  66751. 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);
  66752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66753. }
  66754. if (this._bloomEnabled) {
  66755. // Create down sample X4 post-process
  66756. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66757. // Create bright pass post-process
  66758. this._createBrightPassPostProcess(scene, ratio / 2);
  66759. // Create gaussian blur post-processes (down sampling blurs)
  66760. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66761. // Create texture adder post-process
  66762. this._createTextureAdderPostProcess(scene, ratio);
  66763. // Create depth-of-field source post-process
  66764. 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);
  66765. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66766. }
  66767. if (this._lensFlareEnabled) {
  66768. // Create lens flare post-process
  66769. this._createLensFlarePostProcess(scene, ratio);
  66770. // Create depth-of-field source post-process post lens-flare and disable it now
  66771. 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);
  66772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66773. }
  66774. if (this._hdrEnabled) {
  66775. // Create luminance
  66776. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66777. // Create HDR
  66778. this._createHdrPostProcess(scene, ratio);
  66779. // Create depth-of-field source post-process post hdr and disable it now
  66780. 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);
  66781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66782. }
  66783. if (this._depthOfFieldEnabled) {
  66784. // Create gaussian blur used by depth-of-field
  66785. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66786. // Create depth-of-field post-process
  66787. this._createDepthOfFieldPostProcess(scene, ratio);
  66788. }
  66789. if (this._motionBlurEnabled) {
  66790. // Create motion blur post-process
  66791. this._createMotionBlurPostProcess(scene, ratio);
  66792. }
  66793. if (this._cameras !== null) {
  66794. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66795. }
  66796. };
  66797. // Down Sample X4 Post-Processs
  66798. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66799. var _this = this;
  66800. var downSampleX4Offsets = new Array(32);
  66801. 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);
  66802. this.downSampleX4PostProcess.onApply = function (effect) {
  66803. var id = 0;
  66804. var width = _this.downSampleX4PostProcess.width;
  66805. var height = _this.downSampleX4PostProcess.height;
  66806. for (var i = -2; i < 2; i++) {
  66807. for (var j = -2; j < 2; j++) {
  66808. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66809. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66810. id += 2;
  66811. }
  66812. }
  66813. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66814. };
  66815. // Add to pipeline
  66816. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66817. };
  66818. // Brightpass Post-Process
  66819. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66820. var _this = this;
  66821. var brightOffsets = new Array(8);
  66822. 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);
  66823. this.brightPassPostProcess.onApply = function (effect) {
  66824. var sU = (1.0 / _this.brightPassPostProcess.width);
  66825. var sV = (1.0 / _this.brightPassPostProcess.height);
  66826. brightOffsets[0] = -0.5 * sU;
  66827. brightOffsets[1] = 0.5 * sV;
  66828. brightOffsets[2] = 0.5 * sU;
  66829. brightOffsets[3] = 0.5 * sV;
  66830. brightOffsets[4] = -0.5 * sU;
  66831. brightOffsets[5] = -0.5 * sV;
  66832. brightOffsets[6] = 0.5 * sU;
  66833. brightOffsets[7] = -0.5 * sV;
  66834. effect.setArray2("dsOffsets", brightOffsets);
  66835. effect.setFloat("brightThreshold", _this.brightThreshold);
  66836. };
  66837. // Add to pipeline
  66838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66839. };
  66840. // Create blur H&V post-processes
  66841. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66842. var _this = this;
  66843. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66844. var engine = scene.getEngine();
  66845. 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);
  66846. 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);
  66847. blurX.onActivateObservable.add(function () {
  66848. var dw = blurX.width / engine.getRenderWidth();
  66849. blurX.kernel = _this[blurWidthKey] * dw;
  66850. });
  66851. blurY.onActivateObservable.add(function () {
  66852. var dw = blurY.height / engine.getRenderHeight();
  66853. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66854. });
  66855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66857. this.blurHPostProcesses.push(blurX);
  66858. this.blurVPostProcesses.push(blurY);
  66859. };
  66860. // Create texture adder post-process
  66861. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66862. var _this = this;
  66863. 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);
  66864. this.textureAdderPostProcess.onApply = function (effect) {
  66865. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66866. effect.setTexture("lensSampler", _this.lensTexture);
  66867. effect.setFloat("exposure", _this.exposure);
  66868. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66869. };
  66870. // Add to pipeline
  66871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66872. };
  66873. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66874. var _this = this;
  66875. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66876. geometryRenderer.enablePosition = true;
  66877. var geometry = geometryRenderer.getGBuffer();
  66878. // Base post-process
  66879. 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));
  66880. var depthValues = BABYLON.Vector2.Zero();
  66881. this.volumetricLightPostProcess.onApply = function (effect) {
  66882. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66883. var generator = _this.sourceLight.getShadowGenerator();
  66884. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66885. effect.setTexture("positionSampler", geometry.textures[2]);
  66886. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66887. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66888. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66889. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66890. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66891. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66892. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66893. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66894. effect.setVector2("depthValues", depthValues);
  66895. }
  66896. };
  66897. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66898. // Smooth
  66899. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66900. // Merge
  66901. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66902. this.volumetricLightMergePostProces.onApply = function (effect) {
  66903. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66904. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66905. };
  66906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66907. };
  66908. // Create luminance
  66909. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66910. var _this = this;
  66911. // Create luminance
  66912. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66913. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66914. var offsets = [];
  66915. this.luminancePostProcess.onApply = function (effect) {
  66916. var sU = (1.0 / _this.luminancePostProcess.width);
  66917. var sV = (1.0 / _this.luminancePostProcess.height);
  66918. offsets[0] = -0.5 * sU;
  66919. offsets[1] = 0.5 * sV;
  66920. offsets[2] = 0.5 * sU;
  66921. offsets[3] = 0.5 * sV;
  66922. offsets[4] = -0.5 * sU;
  66923. offsets[5] = -0.5 * sV;
  66924. offsets[6] = 0.5 * sU;
  66925. offsets[7] = -0.5 * sV;
  66926. effect.setArray2("lumOffsets", offsets);
  66927. };
  66928. // Add to pipeline
  66929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66930. // Create down sample luminance
  66931. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66932. var size = Math.pow(3, i);
  66933. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66934. if (i === 0) {
  66935. defines += "#define FINAL_DOWN_SAMPLER";
  66936. }
  66937. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66938. this.luminanceDownSamplePostProcesses.push(postProcess);
  66939. }
  66940. // Create callbacks and add effects
  66941. var lastLuminance = this.luminancePostProcess;
  66942. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66943. var downSampleOffsets = new Array(18);
  66944. pp.onApply = function (effect) {
  66945. if (!lastLuminance) {
  66946. return;
  66947. }
  66948. var id = 0;
  66949. for (var x = -1; x < 2; x++) {
  66950. for (var y = -1; y < 2; y++) {
  66951. downSampleOffsets[id] = x / lastLuminance.width;
  66952. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66953. id += 2;
  66954. }
  66955. }
  66956. effect.setArray2("dsOffsets", downSampleOffsets);
  66957. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66958. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66959. lastLuminance = _this.luminancePostProcess;
  66960. }
  66961. else {
  66962. lastLuminance = pp;
  66963. }
  66964. };
  66965. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66966. pp.onAfterRender = function (effect) {
  66967. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66968. 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);
  66969. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66970. };
  66971. }
  66972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66973. });
  66974. };
  66975. // Create HDR post-process
  66976. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66977. var _this = this;
  66978. 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);
  66979. var outputLiminance = 1;
  66980. var time = 0;
  66981. var lastTime = 0;
  66982. this.hdrPostProcess.onApply = function (effect) {
  66983. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66984. time += scene.getEngine().getDeltaTime();
  66985. if (outputLiminance < 0) {
  66986. outputLiminance = _this._hdrCurrentLuminance;
  66987. }
  66988. else {
  66989. var dt = (lastTime - time) / 1000.0;
  66990. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66991. outputLiminance += _this.hdrDecreaseRate * dt;
  66992. }
  66993. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66994. outputLiminance -= _this.hdrIncreaseRate * dt;
  66995. }
  66996. else {
  66997. outputLiminance = _this._hdrCurrentLuminance;
  66998. }
  66999. }
  67000. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67001. effect.setFloat("averageLuminance", outputLiminance);
  67002. lastTime = time;
  67003. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67004. };
  67005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67006. };
  67007. // Create lens flare post-process
  67008. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67009. var _this = this;
  67010. 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);
  67011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67012. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67013. 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);
  67014. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67015. var resolution = new BABYLON.Vector2(0, 0);
  67016. // Lens flare
  67017. this.lensFlarePostProcess.onApply = function (effect) {
  67018. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67019. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67020. effect.setFloat("strength", _this.lensFlareStrength);
  67021. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67022. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67023. // Shift
  67024. resolution.x = _this.lensFlarePostProcess.width;
  67025. resolution.y = _this.lensFlarePostProcess.height;
  67026. effect.setVector2("resolution", resolution);
  67027. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67028. };
  67029. // Compose
  67030. 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);
  67031. 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);
  67032. this.lensFlareComposePostProcess.onApply = function (effect) {
  67033. if (!_this._scene.activeCamera) {
  67034. return;
  67035. }
  67036. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67037. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67038. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67039. // Lens start rotation matrix
  67040. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67041. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67042. 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));
  67043. camRot *= 4.0;
  67044. 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);
  67045. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67046. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67047. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67048. };
  67049. };
  67050. // Create depth-of-field post-process
  67051. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67052. var _this = this;
  67053. 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);
  67054. this.depthOfFieldPostProcess.onApply = function (effect) {
  67055. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67056. effect.setTexture("depthSampler", _this._getDepthTexture());
  67057. effect.setFloat("distance", _this.depthOfFieldDistance);
  67058. };
  67059. // Add to pipeline
  67060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67061. };
  67062. // Create motion blur post-process
  67063. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67064. var _this = this;
  67065. 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);
  67066. var motionScale = 0;
  67067. var prevViewProjection = BABYLON.Matrix.Identity();
  67068. var invViewProjection = BABYLON.Matrix.Identity();
  67069. var viewProjection = BABYLON.Matrix.Identity();
  67070. var screenSize = BABYLON.Vector2.Zero();
  67071. this.motionBlurPostProcess.onApply = function (effect) {
  67072. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67073. viewProjection.invertToRef(invViewProjection);
  67074. effect.setMatrix("inverseViewProjection", invViewProjection);
  67075. effect.setMatrix("prevViewProjection", prevViewProjection);
  67076. prevViewProjection = viewProjection;
  67077. screenSize.x = _this.motionBlurPostProcess.width;
  67078. screenSize.y = _this.motionBlurPostProcess.height;
  67079. effect.setVector2("screenSize", screenSize);
  67080. motionScale = scene.getEngine().getFps() / 60.0;
  67081. effect.setFloat("motionScale", motionScale);
  67082. effect.setFloat("motionStrength", _this.motionStrength);
  67083. effect.setTexture("depthSampler", _this._getDepthTexture());
  67084. };
  67085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67086. };
  67087. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67088. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67089. var renderer = this._scene.enableGeometryBufferRenderer();
  67090. return renderer.getGBuffer().textures[0];
  67091. }
  67092. return this._scene.enableDepthRenderer().getDepthMap();
  67093. };
  67094. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67095. for (var i = 0; i < this._cameras.length; i++) {
  67096. var camera = this._cameras[i];
  67097. if (this.originalPostProcess) {
  67098. this.originalPostProcess.dispose(camera);
  67099. }
  67100. if (this.downSampleX4PostProcess) {
  67101. this.downSampleX4PostProcess.dispose(camera);
  67102. }
  67103. if (this.brightPassPostProcess) {
  67104. this.brightPassPostProcess.dispose(camera);
  67105. }
  67106. if (this.textureAdderPostProcess) {
  67107. this.textureAdderPostProcess.dispose(camera);
  67108. }
  67109. if (this.textureAdderFinalPostProcess) {
  67110. this.textureAdderFinalPostProcess.dispose(camera);
  67111. }
  67112. if (this.volumetricLightPostProcess) {
  67113. this.volumetricLightPostProcess.dispose(camera);
  67114. }
  67115. if (this.volumetricLightSmoothXPostProcess) {
  67116. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67117. }
  67118. if (this.volumetricLightSmoothYPostProcess) {
  67119. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67120. }
  67121. if (this.volumetricLightMergePostProces) {
  67122. this.volumetricLightMergePostProces.dispose(camera);
  67123. }
  67124. if (this.volumetricLightFinalPostProcess) {
  67125. this.volumetricLightFinalPostProcess.dispose(camera);
  67126. }
  67127. if (this.lensFlarePostProcess) {
  67128. this.lensFlarePostProcess.dispose(camera);
  67129. }
  67130. if (this.lensFlareComposePostProcess) {
  67131. this.lensFlareComposePostProcess.dispose(camera);
  67132. }
  67133. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67134. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67135. }
  67136. if (this.luminancePostProcess) {
  67137. this.luminancePostProcess.dispose(camera);
  67138. }
  67139. if (this.hdrPostProcess) {
  67140. this.hdrPostProcess.dispose(camera);
  67141. }
  67142. if (this.hdrFinalPostProcess) {
  67143. this.hdrFinalPostProcess.dispose(camera);
  67144. }
  67145. if (this.depthOfFieldPostProcess) {
  67146. this.depthOfFieldPostProcess.dispose(camera);
  67147. }
  67148. if (this.motionBlurPostProcess) {
  67149. this.motionBlurPostProcess.dispose(camera);
  67150. }
  67151. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67152. this.blurHPostProcesses[j].dispose(camera);
  67153. }
  67154. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67155. this.blurVPostProcesses[j].dispose(camera);
  67156. }
  67157. }
  67158. this.originalPostProcess = null;
  67159. this.downSampleX4PostProcess = null;
  67160. this.brightPassPostProcess = null;
  67161. this.textureAdderPostProcess = null;
  67162. this.textureAdderFinalPostProcess = null;
  67163. this.volumetricLightPostProcess = null;
  67164. this.volumetricLightSmoothXPostProcess = null;
  67165. this.volumetricLightSmoothYPostProcess = null;
  67166. this.volumetricLightMergePostProces = null;
  67167. this.volumetricLightFinalPostProcess = null;
  67168. this.lensFlarePostProcess = null;
  67169. this.lensFlareComposePostProcess = null;
  67170. this.luminancePostProcess = null;
  67171. this.hdrPostProcess = null;
  67172. this.hdrFinalPostProcess = null;
  67173. this.depthOfFieldPostProcess = null;
  67174. this.motionBlurPostProcess = null;
  67175. this.luminanceDownSamplePostProcesses = [];
  67176. this.blurHPostProcesses = [];
  67177. this.blurVPostProcesses = [];
  67178. };
  67179. // Dispose
  67180. StandardRenderingPipeline.prototype.dispose = function () {
  67181. this._disposePostProcesses();
  67182. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67183. _super.prototype.dispose.call(this);
  67184. };
  67185. // Serialize rendering pipeline
  67186. StandardRenderingPipeline.prototype.serialize = function () {
  67187. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67188. serializationObject.customType = "StandardRenderingPipeline";
  67189. return serializationObject;
  67190. };
  67191. /**
  67192. * Static members
  67193. */
  67194. // Parse serialized pipeline
  67195. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67196. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67197. };
  67198. // Luminance steps
  67199. StandardRenderingPipeline.LuminanceSteps = 6;
  67200. __decorate([
  67201. BABYLON.serialize()
  67202. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67203. __decorate([
  67204. BABYLON.serialize()
  67205. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67206. __decorate([
  67207. BABYLON.serialize()
  67208. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67209. __decorate([
  67210. BABYLON.serialize()
  67211. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67212. __decorate([
  67213. BABYLON.serializeAsTexture("lensTexture")
  67214. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67215. __decorate([
  67216. BABYLON.serialize()
  67217. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67218. __decorate([
  67219. BABYLON.serialize()
  67220. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67221. __decorate([
  67222. BABYLON.serialize()
  67223. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67224. __decorate([
  67225. BABYLON.serialize()
  67226. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67227. __decorate([
  67228. BABYLON.serialize()
  67229. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67230. __decorate([
  67231. BABYLON.serialize()
  67232. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67233. __decorate([
  67234. BABYLON.serializeAsTexture("lensColorTexture")
  67235. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67236. __decorate([
  67237. BABYLON.serialize()
  67238. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67239. __decorate([
  67240. BABYLON.serialize()
  67241. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67242. __decorate([
  67243. BABYLON.serialize()
  67244. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67245. __decorate([
  67246. BABYLON.serialize()
  67247. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67248. __decorate([
  67249. BABYLON.serializeAsTexture("lensStarTexture")
  67250. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67251. __decorate([
  67252. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67253. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67254. __decorate([
  67255. BABYLON.serialize()
  67256. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67257. __decorate([
  67258. BABYLON.serialize()
  67259. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67260. __decorate([
  67261. BABYLON.serialize()
  67262. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67263. __decorate([
  67264. BABYLON.serialize()
  67265. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67266. __decorate([
  67267. BABYLON.serialize()
  67268. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67269. __decorate([
  67270. BABYLON.serialize()
  67271. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67272. __decorate([
  67273. BABYLON.serialize()
  67274. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67275. __decorate([
  67276. BABYLON.serialize()
  67277. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67278. __decorate([
  67279. BABYLON.serialize()
  67280. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67281. __decorate([
  67282. BABYLON.serialize()
  67283. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67284. __decorate([
  67285. BABYLON.serialize()
  67286. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67287. __decorate([
  67288. BABYLON.serialize()
  67289. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67290. return StandardRenderingPipeline;
  67291. }(BABYLON.PostProcessRenderPipeline));
  67292. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67293. })(BABYLON || (BABYLON = {}));
  67294. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67295. var BABYLON;
  67296. (function (BABYLON) {
  67297. var FxaaPostProcess = /** @class */ (function (_super) {
  67298. __extends(FxaaPostProcess, _super);
  67299. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67300. if (camera === void 0) { camera = null; }
  67301. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67302. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67303. _this.onApplyObservable.add(function (effect) {
  67304. var texelSize = _this.texelSize;
  67305. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67306. });
  67307. return _this;
  67308. }
  67309. return FxaaPostProcess;
  67310. }(BABYLON.PostProcess));
  67311. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67312. })(BABYLON || (BABYLON = {}));
  67313. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67314. var BABYLON;
  67315. (function (BABYLON) {
  67316. /**
  67317. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67318. */
  67319. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67320. __extends(CircleOfConfusionPostProcess, _super);
  67321. /**
  67322. * Creates a new instance of @see CircleOfConfusionPostProcess
  67323. * @param name The name of the effect.
  67324. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67325. * @param options The required width/height ratio to downsize to before computing the render pass.
  67326. * @param camera The camera to apply the render pass to.
  67327. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67328. * @param engine The engine which the post process will be applied. (default: current engine)
  67329. * @param reusable If the post process can be reused on the same frame. (default: false)
  67330. * @param textureType Type of textures used when performing the post process. (default: 0)
  67331. */
  67332. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67333. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67334. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67335. /**
  67336. * 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.
  67337. */
  67338. _this.lensSize = 50;
  67339. /**
  67340. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67341. */
  67342. _this.fStop = 1.4;
  67343. /**
  67344. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67345. */
  67346. _this.focusDistance = 2000;
  67347. /**
  67348. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67349. */
  67350. _this.focalLength = 50;
  67351. _this.onApplyObservable.add(function (effect) {
  67352. effect.setTexture("depthSampler", depthTexture);
  67353. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67354. var aperture = _this.lensSize / _this.fStop;
  67355. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67356. effect.setFloat('focusDistance', _this.focusDistance);
  67357. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67358. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67359. });
  67360. return _this;
  67361. }
  67362. return CircleOfConfusionPostProcess;
  67363. }(BABYLON.PostProcess));
  67364. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67365. })(BABYLON || (BABYLON = {}));
  67366. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67367. var BABYLON;
  67368. (function (BABYLON) {
  67369. /**
  67370. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67371. */
  67372. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67373. __extends(DepthOfFieldMergePostProcess, _super);
  67374. /**
  67375. * Creates a new instance of @see CircleOfConfusionPostProcess
  67376. * @param name The name of the effect.
  67377. * @param original The non-blurred image to be modified
  67378. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67379. * @param blurSteps Incrimental bluring post processes.
  67380. * @param options The required width/height ratio to downsize to before computing the render pass.
  67381. * @param camera The camera to apply the render pass to.
  67382. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67383. * @param engine The engine which the post process will be applied. (default: current engine)
  67384. * @param reusable If the post process can be reused on the same frame. (default: false)
  67385. * @param textureType Type of textures used when performing the post process. (default: 0)
  67386. */
  67387. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67388. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67389. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67390. _this.onApplyObservable.add(function (effect) {
  67391. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67392. effect.setTextureFromPostProcess("originalSampler", original);
  67393. blurSteps.forEach(function (step, index) {
  67394. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67395. });
  67396. });
  67397. return _this;
  67398. }
  67399. return DepthOfFieldMergePostProcess;
  67400. }(BABYLON.PostProcess));
  67401. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67402. })(BABYLON || (BABYLON = {}));
  67403. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67404. var BABYLON;
  67405. (function (BABYLON) {
  67406. /**
  67407. * Specifies the level of max blur that should be applied when using the depth of field effect
  67408. */
  67409. var DepthOfFieldEffectBlurLevel;
  67410. (function (DepthOfFieldEffectBlurLevel) {
  67411. /**
  67412. * Subtle blur
  67413. */
  67414. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67415. /**
  67416. * Medium blur
  67417. */
  67418. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67419. /**
  67420. * Large blur
  67421. */
  67422. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67423. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67424. ;
  67425. /**
  67426. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67427. */
  67428. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67429. __extends(DepthOfFieldEffect, _super);
  67430. /**
  67431. * Creates a new instance of @see DepthOfFieldEffect
  67432. * @param scene The scene the effect belongs to.
  67433. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67434. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67435. */
  67436. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67437. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67438. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67439. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67440. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67441. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67442. // Capture circle of confusion texture
  67443. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67444. _this._depthOfFieldPass.autoClear = false;
  67445. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  67446. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67447. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67448. _this._depthOfFieldBlurY = [];
  67449. _this._depthOfFieldBlurX = [];
  67450. var blurCount = 1;
  67451. var kernelSize = 15;
  67452. switch (blurLevel) {
  67453. case DepthOfFieldEffectBlurLevel.High: {
  67454. blurCount = 3;
  67455. kernelSize = 51;
  67456. break;
  67457. }
  67458. case DepthOfFieldEffectBlurLevel.Medium: {
  67459. blurCount = 2;
  67460. kernelSize = 31;
  67461. break;
  67462. }
  67463. default: {
  67464. kernelSize = 15;
  67465. blurCount = 1;
  67466. break;
  67467. }
  67468. }
  67469. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67470. for (var i = 0; i < blurCount; i++) {
  67471. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67472. blurY.autoClear = false;
  67473. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67474. blurX.autoClear = false;
  67475. _this._depthOfFieldBlurY.push(blurY);
  67476. _this._depthOfFieldBlurX.push(blurX);
  67477. }
  67478. // Merge blurred images with original image based on circleOfConfusion
  67479. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67480. _this._depthOfFieldMerge.autoClear = false;
  67481. // Set all post processes on the effect.
  67482. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67483. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67484. effects.push(_this._depthOfFieldBlurY[i]);
  67485. effects.push(_this._depthOfFieldBlurX[i]);
  67486. }
  67487. effects.push(_this._depthOfFieldMerge);
  67488. return effects;
  67489. }, true) || this;
  67490. return _this;
  67491. }
  67492. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67493. get: function () {
  67494. return this._circleOfConfusion.focalLength;
  67495. },
  67496. /**
  67497. * The focal the length of the camera used in the effect
  67498. */
  67499. set: function (value) {
  67500. this._circleOfConfusion.focalLength = value;
  67501. },
  67502. enumerable: true,
  67503. configurable: true
  67504. });
  67505. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67506. get: function () {
  67507. return this._circleOfConfusion.fStop;
  67508. },
  67509. /**
  67510. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67511. */
  67512. set: function (value) {
  67513. this._circleOfConfusion.fStop = value;
  67514. },
  67515. enumerable: true,
  67516. configurable: true
  67517. });
  67518. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67519. get: function () {
  67520. return this._circleOfConfusion.focusDistance;
  67521. },
  67522. /**
  67523. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67524. */
  67525. set: function (value) {
  67526. this._circleOfConfusion.focusDistance = value;
  67527. },
  67528. enumerable: true,
  67529. configurable: true
  67530. });
  67531. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67532. get: function () {
  67533. return this._circleOfConfusion.lensSize;
  67534. },
  67535. /**
  67536. * 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.
  67537. */
  67538. set: function (value) {
  67539. this._circleOfConfusion.lensSize = value;
  67540. },
  67541. enumerable: true,
  67542. configurable: true
  67543. });
  67544. /**
  67545. * Disposes each of the internal effects for a given camera.
  67546. * @param camera The camera to dispose the effect on.
  67547. */
  67548. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67549. this._depthOfFieldPass.dispose(camera);
  67550. this._circleOfConfusion.dispose(camera);
  67551. this._depthOfFieldBlurX.forEach(function (element) {
  67552. element.dispose(camera);
  67553. });
  67554. this._depthOfFieldBlurY.forEach(function (element) {
  67555. element.dispose(camera);
  67556. });
  67557. this._depthOfFieldMerge.dispose(camera);
  67558. };
  67559. return DepthOfFieldEffect;
  67560. }(BABYLON.PostProcessRenderEffect));
  67561. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67562. })(BABYLON || (BABYLON = {}));
  67563. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67564. var BABYLON;
  67565. (function (BABYLON) {
  67566. /**
  67567. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67568. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67569. */
  67570. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67571. __extends(DefaultRenderingPipeline, _super);
  67572. /**
  67573. * @constructor
  67574. * @param {string} name - The rendering pipeline name
  67575. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67576. * @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)
  67577. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67578. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67579. */
  67580. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67581. if (automaticBuild === void 0) { automaticBuild = true; }
  67582. var _this = _super.call(this, scene.getEngine(), name) || this;
  67583. /**
  67584. * ID of the pass post process used for bloom,
  67585. */
  67586. _this.PassPostProcessId = "PassPostProcessEffect";
  67587. /**
  67588. * ID of the highlight post process used for bloom,
  67589. */
  67590. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67591. /**
  67592. * ID of the blurX post process used for bloom,
  67593. */
  67594. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67595. /**
  67596. * ID of the blurY post process used for bloom,
  67597. */
  67598. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67599. /**
  67600. * ID of the copy back post process used for bloom,
  67601. */
  67602. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67603. /**
  67604. * ID of the image processing post process;
  67605. */
  67606. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67607. /**
  67608. * ID of the Fast Approximate Anti-Aliasing post process;
  67609. */
  67610. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67611. /**
  67612. * ID of the final merge post process;
  67613. */
  67614. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67615. /**
  67616. * Animations which can be used to tweak settings over a period of time
  67617. */
  67618. _this.animations = [];
  67619. // Values
  67620. _this._bloomEnabled = false;
  67621. _this._depthOfFieldEnabled = false;
  67622. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67623. _this._fxaaEnabled = false;
  67624. _this._imageProcessingEnabled = true;
  67625. _this._bloomScale = 0.6;
  67626. _this._buildAllowed = true;
  67627. /**
  67628. * Specifies the size of the bloom blur kernel, relative to the final output size
  67629. */
  67630. _this.bloomKernel = 64;
  67631. /**
  67632. * Specifies the weight of the bloom in the final rendering
  67633. */
  67634. _this._bloomWeight = 0.15;
  67635. _this._cameras = cameras || [];
  67636. _this._buildAllowed = automaticBuild;
  67637. // Initialize
  67638. _this._scene = scene;
  67639. var caps = _this._scene.getEngine().getCaps();
  67640. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67641. // Misc
  67642. if (_this._hdr) {
  67643. if (caps.textureHalfFloatRender) {
  67644. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67645. }
  67646. else if (caps.textureFloatRender) {
  67647. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67648. }
  67649. }
  67650. else {
  67651. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67652. }
  67653. // Attach
  67654. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67655. _this._buildPipeline();
  67656. return _this;
  67657. }
  67658. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67659. get: function () {
  67660. return this._bloomWeight;
  67661. },
  67662. /**
  67663. * The strength of the bloom.
  67664. */
  67665. set: function (value) {
  67666. if (this._bloomWeight === value) {
  67667. return;
  67668. }
  67669. this._bloomWeight = value;
  67670. if (this._hdr && this.copyBack) {
  67671. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67672. }
  67673. },
  67674. enumerable: true,
  67675. configurable: true
  67676. });
  67677. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67678. get: function () {
  67679. return this._bloomScale;
  67680. },
  67681. /**
  67682. * The scale of the bloom, lower value will provide better performance.
  67683. */
  67684. set: function (value) {
  67685. if (this._bloomScale === value) {
  67686. return;
  67687. }
  67688. this._bloomScale = value;
  67689. this._buildPipeline();
  67690. },
  67691. enumerable: true,
  67692. configurable: true
  67693. });
  67694. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67695. get: function () {
  67696. return this._bloomEnabled;
  67697. },
  67698. /**
  67699. * Enable or disable the bloom from the pipeline
  67700. */
  67701. set: function (enabled) {
  67702. if (this._bloomEnabled === enabled) {
  67703. return;
  67704. }
  67705. this._bloomEnabled = enabled;
  67706. this._buildPipeline();
  67707. },
  67708. enumerable: true,
  67709. configurable: true
  67710. });
  67711. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67712. /**
  67713. * If the depth of field is enabled.
  67714. */
  67715. get: function () {
  67716. return this._depthOfFieldEnabled;
  67717. },
  67718. set: function (enabled) {
  67719. if (this._depthOfFieldEnabled === enabled) {
  67720. return;
  67721. }
  67722. this._depthOfFieldEnabled = enabled;
  67723. this._buildPipeline();
  67724. },
  67725. enumerable: true,
  67726. configurable: true
  67727. });
  67728. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67729. /**
  67730. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67731. */
  67732. get: function () {
  67733. return this._depthOfFieldBlurLevel;
  67734. },
  67735. set: function (value) {
  67736. if (this._depthOfFieldBlurLevel === value) {
  67737. return;
  67738. }
  67739. this._depthOfFieldBlurLevel = value;
  67740. this._buildPipeline();
  67741. },
  67742. enumerable: true,
  67743. configurable: true
  67744. });
  67745. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67746. get: function () {
  67747. return this._fxaaEnabled;
  67748. },
  67749. /**
  67750. * If the anti aliasing is enabled.
  67751. */
  67752. set: function (enabled) {
  67753. if (this._fxaaEnabled === enabled) {
  67754. return;
  67755. }
  67756. this._fxaaEnabled = enabled;
  67757. this._buildPipeline();
  67758. },
  67759. enumerable: true,
  67760. configurable: true
  67761. });
  67762. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67763. get: function () {
  67764. return this._imageProcessingEnabled;
  67765. },
  67766. /**
  67767. * If image processing is enabled.
  67768. */
  67769. set: function (enabled) {
  67770. if (this._imageProcessingEnabled === enabled) {
  67771. return;
  67772. }
  67773. this._imageProcessingEnabled = enabled;
  67774. this._buildPipeline();
  67775. },
  67776. enumerable: true,
  67777. configurable: true
  67778. });
  67779. /**
  67780. * Force the compilation of the entire pipeline.
  67781. */
  67782. DefaultRenderingPipeline.prototype.prepare = function () {
  67783. var previousState = this._buildAllowed;
  67784. this._buildAllowed = true;
  67785. this._buildPipeline();
  67786. this._buildAllowed = previousState;
  67787. };
  67788. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67789. var _this = this;
  67790. if (!this._buildAllowed) {
  67791. return;
  67792. }
  67793. var engine = this._scene.getEngine();
  67794. this._disposePostProcesses();
  67795. this._reset();
  67796. if (this.depthOfFieldEnabled) {
  67797. // Enable and get current depth map
  67798. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  67799. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67800. this.addEffect(this.depthOfField);
  67801. }
  67802. if (this.bloomEnabled) {
  67803. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67804. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67805. if (!this._hdr) {
  67806. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67807. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67808. this.highlights.autoClear = false;
  67809. this.highlights.alwaysForcePOT = true;
  67810. }
  67811. 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);
  67812. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67813. this.blurX.alwaysForcePOT = true;
  67814. this.blurX.autoClear = false;
  67815. this.blurX.onActivateObservable.add(function () {
  67816. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67817. _this.blurX.kernel = _this.bloomKernel * dw;
  67818. });
  67819. 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);
  67820. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67821. this.blurY.alwaysForcePOT = true;
  67822. this.blurY.autoClear = false;
  67823. this.blurY.onActivateObservable.add(function () {
  67824. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67825. _this.blurY.kernel = _this.bloomKernel * dh;
  67826. });
  67827. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67828. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67829. this.copyBack.alwaysForcePOT = true;
  67830. if (this._hdr) {
  67831. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67832. var w = this.bloomWeight;
  67833. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67834. }
  67835. else {
  67836. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67837. }
  67838. this.copyBack.autoClear = false;
  67839. }
  67840. if (this._imageProcessingEnabled) {
  67841. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67842. if (this._hdr) {
  67843. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67844. }
  67845. else {
  67846. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67847. }
  67848. }
  67849. if (this.fxaaEnabled) {
  67850. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67851. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67852. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67853. }
  67854. else if (this._hdr && this.imageProcessing) {
  67855. this.finalMerge = this.imageProcessing;
  67856. }
  67857. else {
  67858. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67859. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67860. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67861. }
  67862. if (this.bloomEnabled) {
  67863. if (this._hdr) {
  67864. this.copyBack.shareOutputWith(this.blurX);
  67865. if (this.imageProcessing) {
  67866. this.imageProcessing.shareOutputWith(this.pass);
  67867. this.imageProcessing.autoClear = false;
  67868. }
  67869. else if (this.fxaa) {
  67870. this.fxaa.shareOutputWith(this.pass);
  67871. }
  67872. else {
  67873. this.finalMerge.shareOutputWith(this.pass);
  67874. }
  67875. }
  67876. else {
  67877. if (this.fxaa) {
  67878. this.fxaa.shareOutputWith(this.pass);
  67879. }
  67880. else {
  67881. this.finalMerge.shareOutputWith(this.pass);
  67882. }
  67883. }
  67884. }
  67885. if (this._cameras !== null) {
  67886. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67887. }
  67888. };
  67889. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67890. for (var i = 0; i < this._cameras.length; i++) {
  67891. var camera = this._cameras[i];
  67892. if (this.pass) {
  67893. this.pass.dispose(camera);
  67894. }
  67895. if (this.highlights) {
  67896. this.highlights.dispose(camera);
  67897. }
  67898. if (this.blurX) {
  67899. this.blurX.dispose(camera);
  67900. }
  67901. if (this.blurY) {
  67902. this.blurY.dispose(camera);
  67903. }
  67904. if (this.copyBack) {
  67905. this.copyBack.dispose(camera);
  67906. }
  67907. if (this.imageProcessing) {
  67908. this.imageProcessing.dispose(camera);
  67909. }
  67910. if (this.fxaa) {
  67911. this.fxaa.dispose(camera);
  67912. }
  67913. if (this.finalMerge) {
  67914. this.finalMerge.dispose(camera);
  67915. }
  67916. if (this.depthOfField) {
  67917. this.depthOfField.disposeEffects(camera);
  67918. }
  67919. }
  67920. this.pass = null;
  67921. this.highlights = null;
  67922. this.blurX = null;
  67923. this.blurY = null;
  67924. this.copyBack = null;
  67925. this.imageProcessing = null;
  67926. this.fxaa = null;
  67927. this.finalMerge = null;
  67928. this.depthOfField = null;
  67929. };
  67930. /**
  67931. * Dispose of the pipeline and stop all post processes
  67932. */
  67933. DefaultRenderingPipeline.prototype.dispose = function () {
  67934. this._disposePostProcesses();
  67935. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67936. _super.prototype.dispose.call(this);
  67937. };
  67938. /**
  67939. * Serialize the rendering pipeline (Used when exporting)
  67940. * @returns the serialized object
  67941. */
  67942. DefaultRenderingPipeline.prototype.serialize = function () {
  67943. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67944. serializationObject.customType = "DefaultRenderingPipeline";
  67945. return serializationObject;
  67946. };
  67947. /**
  67948. * Parse the serialized pipeline
  67949. * @param source Source pipeline.
  67950. * @param scene The scene to load the pipeline to.
  67951. * @param rootUrl The URL of the serialized pipeline.
  67952. * @returns An instantiated pipeline from the serialized object.
  67953. */
  67954. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67955. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67956. };
  67957. __decorate([
  67958. BABYLON.serialize()
  67959. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67960. __decorate([
  67961. BABYLON.serialize()
  67962. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67963. __decorate([
  67964. BABYLON.serialize()
  67965. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67966. __decorate([
  67967. BABYLON.serialize()
  67968. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67969. __decorate([
  67970. BABYLON.serialize()
  67971. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67972. __decorate([
  67973. BABYLON.serialize()
  67974. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67975. __decorate([
  67976. BABYLON.serialize()
  67977. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67978. __decorate([
  67979. BABYLON.serialize()
  67980. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67981. __decorate([
  67982. BABYLON.serialize()
  67983. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67984. __decorate([
  67985. BABYLON.serialize()
  67986. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67987. return DefaultRenderingPipeline;
  67988. }(BABYLON.PostProcessRenderPipeline));
  67989. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67990. })(BABYLON || (BABYLON = {}));
  67991. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67992. var BABYLON;
  67993. (function (BABYLON) {
  67994. /**
  67995. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67996. */
  67997. var GeometryBufferRenderer = /** @class */ (function () {
  67998. /**
  67999. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68000. * @param scene The scene the buffer belongs to
  68001. * @param ratio How big is the buffer related to the main canvas.
  68002. */
  68003. function GeometryBufferRenderer(scene, ratio) {
  68004. if (ratio === void 0) { ratio = 1; }
  68005. this._enablePosition = false;
  68006. this._scene = scene;
  68007. this._ratio = ratio;
  68008. // Render target
  68009. this._createRenderTargets();
  68010. }
  68011. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68012. /**
  68013. * Set the render list (meshes to be rendered) used in the G buffer.
  68014. */
  68015. set: function (meshes) {
  68016. this._multiRenderTarget.renderList = meshes;
  68017. },
  68018. enumerable: true,
  68019. configurable: true
  68020. });
  68021. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68022. /**
  68023. * Gets wether or not G buffer are supported by the running hardware.
  68024. * This requires draw buffer supports
  68025. */
  68026. get: function () {
  68027. return this._multiRenderTarget.isSupported;
  68028. },
  68029. enumerable: true,
  68030. configurable: true
  68031. });
  68032. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68033. /**
  68034. * Gets wether or not position are enabled for the G buffer.
  68035. */
  68036. get: function () {
  68037. return this._enablePosition;
  68038. },
  68039. /**
  68040. * Sets wether or not position are enabled for the G buffer.
  68041. */
  68042. set: function (enable) {
  68043. this._enablePosition = enable;
  68044. this.dispose();
  68045. this._createRenderTargets();
  68046. },
  68047. enumerable: true,
  68048. configurable: true
  68049. });
  68050. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68051. /**
  68052. * Gets the scene associated with the buffer.
  68053. */
  68054. get: function () {
  68055. return this._scene;
  68056. },
  68057. enumerable: true,
  68058. configurable: true
  68059. });
  68060. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68061. /**
  68062. * Gets the ratio used by the buffer during its creation.
  68063. * How big is the buffer related to the main canvas.
  68064. */
  68065. get: function () {
  68066. return this._ratio;
  68067. },
  68068. enumerable: true,
  68069. configurable: true
  68070. });
  68071. /**
  68072. * Checks wether everything is ready to render a submesh to the G buffer.
  68073. * @param subMesh the submesh to check readiness for
  68074. * @param useInstances is the mesh drawn using instance or not
  68075. * @returns true if ready otherwise false
  68076. */
  68077. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68078. var material = subMesh.getMaterial();
  68079. if (material && material.disableDepthWrite) {
  68080. return false;
  68081. }
  68082. var defines = [];
  68083. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68084. var mesh = subMesh.getMesh();
  68085. // Alpha test
  68086. if (material && material.needAlphaTesting()) {
  68087. defines.push("#define ALPHATEST");
  68088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68089. attribs.push(BABYLON.VertexBuffer.UVKind);
  68090. defines.push("#define UV1");
  68091. }
  68092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68094. defines.push("#define UV2");
  68095. }
  68096. }
  68097. // Buffers
  68098. if (this._enablePosition) {
  68099. defines.push("#define POSITION");
  68100. }
  68101. // Bones
  68102. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68105. if (mesh.numBoneInfluencers > 4) {
  68106. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68107. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68108. }
  68109. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68110. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68111. }
  68112. else {
  68113. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68114. }
  68115. // Instances
  68116. if (useInstances) {
  68117. defines.push("#define INSTANCES");
  68118. attribs.push("world0");
  68119. attribs.push("world1");
  68120. attribs.push("world2");
  68121. attribs.push("world3");
  68122. }
  68123. // Get correct effect
  68124. var join = defines.join("\n");
  68125. if (this._cachedDefines !== join) {
  68126. this._cachedDefines = join;
  68127. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68128. }
  68129. return this._effect.isReady();
  68130. };
  68131. /**
  68132. * Gets the current underlying G Buffer.
  68133. * @returns the buffer
  68134. */
  68135. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68136. return this._multiRenderTarget;
  68137. };
  68138. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68139. /**
  68140. * Gets the number of samples used to render the buffer (anti aliasing).
  68141. */
  68142. get: function () {
  68143. return this._multiRenderTarget.samples;
  68144. },
  68145. /**
  68146. * Sets the number of samples used to render the buffer (anti aliasing).
  68147. */
  68148. set: function (value) {
  68149. this._multiRenderTarget.samples = value;
  68150. },
  68151. enumerable: true,
  68152. configurable: true
  68153. });
  68154. /**
  68155. * Disposes the renderer and frees up associated resources.
  68156. */
  68157. GeometryBufferRenderer.prototype.dispose = function () {
  68158. this.getGBuffer().dispose();
  68159. };
  68160. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68161. var _this = this;
  68162. var engine = this._scene.getEngine();
  68163. var count = this._enablePosition ? 3 : 2;
  68164. 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 });
  68165. if (!this.isSupported) {
  68166. return;
  68167. }
  68168. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68169. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68170. this._multiRenderTarget.refreshRate = 1;
  68171. this._multiRenderTarget.renderParticles = false;
  68172. this._multiRenderTarget.renderList = null;
  68173. // set default depth value to 1.0 (far away)
  68174. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68175. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68176. });
  68177. // Custom render function
  68178. var renderSubMesh = function (subMesh) {
  68179. var mesh = subMesh.getRenderingMesh();
  68180. var scene = _this._scene;
  68181. var engine = scene.getEngine();
  68182. var material = subMesh.getMaterial();
  68183. if (!material) {
  68184. return;
  68185. }
  68186. // Culling
  68187. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68188. // Managing instances
  68189. var batch = mesh._getInstancesRenderList(subMesh._id);
  68190. if (batch.mustReturn) {
  68191. return;
  68192. }
  68193. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68194. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68195. engine.enableEffect(_this._effect);
  68196. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68197. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68198. _this._effect.setMatrix("view", scene.getViewMatrix());
  68199. // Alpha test
  68200. if (material && material.needAlphaTesting()) {
  68201. var alphaTexture = material.getAlphaTestTexture();
  68202. if (alphaTexture) {
  68203. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68204. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68205. }
  68206. }
  68207. // Bones
  68208. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68209. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68210. }
  68211. // Draw
  68212. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68213. }
  68214. };
  68215. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68216. var index;
  68217. if (depthOnlySubMeshes.length) {
  68218. engine.setColorWrite(false);
  68219. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68220. renderSubMesh(depthOnlySubMeshes.data[index]);
  68221. }
  68222. engine.setColorWrite(true);
  68223. }
  68224. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68225. renderSubMesh(opaqueSubMeshes.data[index]);
  68226. }
  68227. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68228. renderSubMesh(alphaTestSubMeshes.data[index]);
  68229. }
  68230. };
  68231. };
  68232. return GeometryBufferRenderer;
  68233. }());
  68234. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68235. })(BABYLON || (BABYLON = {}));
  68236. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68237. var BABYLON;
  68238. (function (BABYLON) {
  68239. var RefractionPostProcess = /** @class */ (function (_super) {
  68240. __extends(RefractionPostProcess, _super);
  68241. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68242. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68243. _this.color = color;
  68244. _this.depth = depth;
  68245. _this.colorLevel = colorLevel;
  68246. _this._ownRefractionTexture = true;
  68247. _this.onActivateObservable.add(function (cam) {
  68248. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68249. });
  68250. _this.onApplyObservable.add(function (effect) {
  68251. effect.setColor3("baseColor", _this.color);
  68252. effect.setFloat("depth", _this.depth);
  68253. effect.setFloat("colorLevel", _this.colorLevel);
  68254. effect.setTexture("refractionSampler", _this._refTexture);
  68255. });
  68256. return _this;
  68257. }
  68258. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68259. /**
  68260. * Gets or sets the refraction texture
  68261. * Please note that you are responsible for disposing the texture if you set it manually
  68262. */
  68263. get: function () {
  68264. return this._refTexture;
  68265. },
  68266. set: function (value) {
  68267. if (this._refTexture && this._ownRefractionTexture) {
  68268. this._refTexture.dispose();
  68269. }
  68270. this._refTexture = value;
  68271. this._ownRefractionTexture = false;
  68272. },
  68273. enumerable: true,
  68274. configurable: true
  68275. });
  68276. // Methods
  68277. RefractionPostProcess.prototype.dispose = function (camera) {
  68278. if (this._refTexture && this._ownRefractionTexture) {
  68279. this._refTexture.dispose();
  68280. this._refTexture = null;
  68281. }
  68282. _super.prototype.dispose.call(this, camera);
  68283. };
  68284. return RefractionPostProcess;
  68285. }(BABYLON.PostProcess));
  68286. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68287. })(BABYLON || (BABYLON = {}));
  68288. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68289. var BABYLON;
  68290. (function (BABYLON) {
  68291. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68292. __extends(BlackAndWhitePostProcess, _super);
  68293. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68294. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68295. _this.degree = 1;
  68296. _this.onApplyObservable.add(function (effect) {
  68297. effect.setFloat("degree", _this.degree);
  68298. });
  68299. return _this;
  68300. }
  68301. return BlackAndWhitePostProcess;
  68302. }(BABYLON.PostProcess));
  68303. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68304. })(BABYLON || (BABYLON = {}));
  68305. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68306. var BABYLON;
  68307. (function (BABYLON) {
  68308. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68309. __extends(ConvolutionPostProcess, _super);
  68310. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  68311. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  68312. _this.kernel = kernel;
  68313. _this.onApply = function (effect) {
  68314. effect.setFloat2("screenSize", _this.width, _this.height);
  68315. effect.setArray("kernel", _this.kernel);
  68316. };
  68317. return _this;
  68318. }
  68319. // Statics
  68320. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68321. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68322. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68323. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68324. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68325. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68326. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68327. return ConvolutionPostProcess;
  68328. }(BABYLON.PostProcess));
  68329. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68330. })(BABYLON || (BABYLON = {}));
  68331. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68332. var BABYLON;
  68333. (function (BABYLON) {
  68334. var FilterPostProcess = /** @class */ (function (_super) {
  68335. __extends(FilterPostProcess, _super);
  68336. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68337. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68338. _this.kernelMatrix = kernelMatrix;
  68339. _this.onApply = function (effect) {
  68340. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68341. };
  68342. return _this;
  68343. }
  68344. return FilterPostProcess;
  68345. }(BABYLON.PostProcess));
  68346. BABYLON.FilterPostProcess = FilterPostProcess;
  68347. })(BABYLON || (BABYLON = {}));
  68348. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68349. var BABYLON;
  68350. (function (BABYLON) {
  68351. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68352. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68353. __extends(VolumetricLightScatteringPostProcess, _super);
  68354. /**
  68355. * @constructor
  68356. * @param {string} name - The post-process name
  68357. * @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)
  68358. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68359. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68360. * @param {number} samples - The post-process quality, default 100
  68361. * @param {number} samplingMode - The post-process filtering mode
  68362. * @param {BABYLON.Engine} engine - The babylon engine
  68363. * @param {boolean} reusable - If the post-process is reusable
  68364. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68365. */
  68366. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68367. if (samples === void 0) { samples = 100; }
  68368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68369. 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;
  68370. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68371. /**
  68372. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68373. * @type {Vector3}
  68374. */
  68375. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68376. /**
  68377. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68378. * @type {boolean}
  68379. */
  68380. _this.useCustomMeshPosition = false;
  68381. /**
  68382. * If the post-process should inverse the light scattering direction
  68383. * @type {boolean}
  68384. */
  68385. _this.invert = true;
  68386. /**
  68387. * Array containing the excluded meshes not rendered in the internal pass
  68388. */
  68389. _this.excludedMeshes = new Array();
  68390. /**
  68391. * Controls the overall intensity of the post-process
  68392. * @type {number}
  68393. */
  68394. _this.exposure = 0.3;
  68395. /**
  68396. * Dissipates each sample's contribution in range [0, 1]
  68397. * @type {number}
  68398. */
  68399. _this.decay = 0.96815;
  68400. /**
  68401. * Controls the overall intensity of each sample
  68402. * @type {number}
  68403. */
  68404. _this.weight = 0.58767;
  68405. /**
  68406. * Controls the density of each sample
  68407. * @type {number}
  68408. */
  68409. _this.density = 0.926;
  68410. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68411. engine = scene.getEngine();
  68412. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68413. // Configure mesh
  68414. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68415. // Configure
  68416. _this._createPass(scene, ratio.passRatio || ratio);
  68417. _this.onActivate = function (camera) {
  68418. if (!_this.isSupported) {
  68419. _this.dispose(camera);
  68420. }
  68421. _this.onActivate = null;
  68422. };
  68423. _this.onApplyObservable.add(function (effect) {
  68424. _this._updateMeshScreenCoordinates(scene);
  68425. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68426. effect.setFloat("exposure", _this.exposure);
  68427. effect.setFloat("decay", _this.decay);
  68428. effect.setFloat("weight", _this.weight);
  68429. effect.setFloat("density", _this.density);
  68430. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68431. });
  68432. return _this;
  68433. }
  68434. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68435. get: function () {
  68436. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68437. return false;
  68438. },
  68439. set: function (useDiffuseColor) {
  68440. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68441. },
  68442. enumerable: true,
  68443. configurable: true
  68444. });
  68445. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68446. return "VolumetricLightScatteringPostProcess";
  68447. };
  68448. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68449. var mesh = subMesh.getMesh();
  68450. // Render this.mesh as default
  68451. if (mesh === this.mesh && mesh.material) {
  68452. return mesh.material.isReady(mesh);
  68453. }
  68454. var defines = [];
  68455. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68456. var material = subMesh.getMaterial();
  68457. // Alpha test
  68458. if (material) {
  68459. if (material.needAlphaTesting()) {
  68460. defines.push("#define ALPHATEST");
  68461. }
  68462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68463. attribs.push(BABYLON.VertexBuffer.UVKind);
  68464. defines.push("#define UV1");
  68465. }
  68466. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68467. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68468. defines.push("#define UV2");
  68469. }
  68470. }
  68471. // Bones
  68472. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68475. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68476. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68477. }
  68478. else {
  68479. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68480. }
  68481. // Instances
  68482. if (useInstances) {
  68483. defines.push("#define INSTANCES");
  68484. attribs.push("world0");
  68485. attribs.push("world1");
  68486. attribs.push("world2");
  68487. attribs.push("world3");
  68488. }
  68489. // Get correct effect
  68490. var join = defines.join("\n");
  68491. if (this._cachedDefines !== join) {
  68492. this._cachedDefines = join;
  68493. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68494. }
  68495. return this._volumetricLightScatteringPass.isReady();
  68496. };
  68497. /**
  68498. * Sets the new light position for light scattering effect
  68499. * @param {BABYLON.Vector3} The new custom light position
  68500. */
  68501. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68502. this.customMeshPosition = position;
  68503. };
  68504. /**
  68505. * Returns the light position for light scattering effect
  68506. * @return {BABYLON.Vector3} The custom light position
  68507. */
  68508. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68509. return this.customMeshPosition;
  68510. };
  68511. /**
  68512. * Disposes the internal assets and detaches the post-process from the camera
  68513. */
  68514. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68515. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68516. if (rttIndex !== -1) {
  68517. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68518. }
  68519. this._volumetricLightScatteringRTT.dispose();
  68520. _super.prototype.dispose.call(this, camera);
  68521. };
  68522. /**
  68523. * Returns the render target texture used by the post-process
  68524. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68525. */
  68526. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68527. return this._volumetricLightScatteringRTT;
  68528. };
  68529. // Private methods
  68530. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68531. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68532. return true;
  68533. }
  68534. return false;
  68535. };
  68536. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68537. var _this = this;
  68538. var engine = scene.getEngine();
  68539. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68540. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68541. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68542. this._volumetricLightScatteringRTT.renderList = null;
  68543. this._volumetricLightScatteringRTT.renderParticles = false;
  68544. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68545. var camera = this.getCamera();
  68546. if (camera) {
  68547. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68548. }
  68549. else {
  68550. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68551. }
  68552. // Custom render function for submeshes
  68553. var renderSubMesh = function (subMesh) {
  68554. var mesh = subMesh.getRenderingMesh();
  68555. if (_this._meshExcluded(mesh)) {
  68556. return;
  68557. }
  68558. var material = subMesh.getMaterial();
  68559. if (!material) {
  68560. return;
  68561. }
  68562. var scene = mesh.getScene();
  68563. var engine = scene.getEngine();
  68564. // Culling
  68565. engine.setState(material.backFaceCulling);
  68566. // Managing instances
  68567. var batch = mesh._getInstancesRenderList(subMesh._id);
  68568. if (batch.mustReturn) {
  68569. return;
  68570. }
  68571. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68572. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68573. var effect = _this._volumetricLightScatteringPass;
  68574. if (mesh === _this.mesh) {
  68575. if (subMesh.effect) {
  68576. effect = subMesh.effect;
  68577. }
  68578. else {
  68579. effect = material.getEffect();
  68580. }
  68581. }
  68582. engine.enableEffect(effect);
  68583. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68584. if (mesh === _this.mesh) {
  68585. material.bind(mesh.getWorldMatrix(), mesh);
  68586. }
  68587. else {
  68588. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68589. // Alpha test
  68590. if (material && material.needAlphaTesting()) {
  68591. var alphaTexture = material.getAlphaTestTexture();
  68592. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68593. if (alphaTexture) {
  68594. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68595. }
  68596. }
  68597. // Bones
  68598. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68599. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68600. }
  68601. }
  68602. // Draw
  68603. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68604. }
  68605. };
  68606. // Render target texture callbacks
  68607. var savedSceneClearColor;
  68608. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68609. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68610. savedSceneClearColor = scene.clearColor;
  68611. scene.clearColor = sceneClearColor;
  68612. });
  68613. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68614. scene.clearColor = savedSceneClearColor;
  68615. });
  68616. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68617. var engine = scene.getEngine();
  68618. var index;
  68619. if (depthOnlySubMeshes.length) {
  68620. engine.setColorWrite(false);
  68621. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68622. renderSubMesh(depthOnlySubMeshes.data[index]);
  68623. }
  68624. engine.setColorWrite(true);
  68625. }
  68626. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68627. renderSubMesh(opaqueSubMeshes.data[index]);
  68628. }
  68629. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68630. renderSubMesh(alphaTestSubMeshes.data[index]);
  68631. }
  68632. if (transparentSubMeshes.length) {
  68633. // Sort sub meshes
  68634. for (index = 0; index < transparentSubMeshes.length; index++) {
  68635. var submesh = transparentSubMeshes.data[index];
  68636. var boundingInfo = submesh.getBoundingInfo();
  68637. if (boundingInfo && scene.activeCamera) {
  68638. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68639. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68640. }
  68641. }
  68642. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68643. sortedArray.sort(function (a, b) {
  68644. // Alpha index first
  68645. if (a._alphaIndex > b._alphaIndex) {
  68646. return 1;
  68647. }
  68648. if (a._alphaIndex < b._alphaIndex) {
  68649. return -1;
  68650. }
  68651. // Then distance to camera
  68652. if (a._distanceToCamera < b._distanceToCamera) {
  68653. return 1;
  68654. }
  68655. if (a._distanceToCamera > b._distanceToCamera) {
  68656. return -1;
  68657. }
  68658. return 0;
  68659. });
  68660. // Render sub meshes
  68661. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68662. for (index = 0; index < sortedArray.length; index++) {
  68663. renderSubMesh(sortedArray[index]);
  68664. }
  68665. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68666. }
  68667. };
  68668. };
  68669. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68670. var transform = scene.getTransformMatrix();
  68671. var meshPosition;
  68672. if (this.useCustomMeshPosition) {
  68673. meshPosition = this.customMeshPosition;
  68674. }
  68675. else if (this.attachedNode) {
  68676. meshPosition = this.attachedNode.position;
  68677. }
  68678. else {
  68679. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68680. }
  68681. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68682. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68683. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68684. if (this.invert)
  68685. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68686. };
  68687. // Static methods
  68688. /**
  68689. * Creates a default mesh for the Volumeric Light Scattering post-process
  68690. * @param {string} The mesh name
  68691. * @param {BABYLON.Scene} The scene where to create the mesh
  68692. * @return {BABYLON.Mesh} the default mesh
  68693. */
  68694. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68695. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68696. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68697. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68698. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  68699. mesh.material = material;
  68700. return mesh;
  68701. };
  68702. __decorate([
  68703. BABYLON.serializeAsVector3()
  68704. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  68705. __decorate([
  68706. BABYLON.serialize()
  68707. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  68708. __decorate([
  68709. BABYLON.serialize()
  68710. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  68711. __decorate([
  68712. BABYLON.serializeAsMeshReference()
  68713. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68714. __decorate([
  68715. BABYLON.serialize()
  68716. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68717. __decorate([
  68718. BABYLON.serialize()
  68719. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68720. __decorate([
  68721. BABYLON.serialize()
  68722. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68723. __decorate([
  68724. BABYLON.serialize()
  68725. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68726. __decorate([
  68727. BABYLON.serialize()
  68728. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68729. return VolumetricLightScatteringPostProcess;
  68730. }(BABYLON.PostProcess));
  68731. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68732. })(BABYLON || (BABYLON = {}));
  68733. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68734. //
  68735. // This post-process allows the modification of rendered colors by using
  68736. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68737. //
  68738. // The object needs to be provided an url to a texture containing the color
  68739. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68740. // Use an image editing software to tweak the LUT to match your needs.
  68741. //
  68742. // For an example of a color LUT, see here:
  68743. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68744. // For explanations on color grading, see here:
  68745. // http://udn.epicgames.com/Three/ColorGrading.html
  68746. //
  68747. var BABYLON;
  68748. (function (BABYLON) {
  68749. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  68750. __extends(ColorCorrectionPostProcess, _super);
  68751. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  68752. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  68753. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68754. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  68755. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68756. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68757. _this.onApply = function (effect) {
  68758. effect.setTexture("colorTable", _this._colorTableTexture);
  68759. };
  68760. return _this;
  68761. }
  68762. return ColorCorrectionPostProcess;
  68763. }(BABYLON.PostProcess));
  68764. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  68765. })(BABYLON || (BABYLON = {}));
  68766. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  68767. var BABYLON;
  68768. (function (BABYLON) {
  68769. var TonemappingOperator;
  68770. (function (TonemappingOperator) {
  68771. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  68772. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  68773. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  68774. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  68775. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  68776. ;
  68777. var TonemapPostProcess = /** @class */ (function (_super) {
  68778. __extends(TonemapPostProcess, _super);
  68779. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  68780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68781. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68782. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  68783. _this._operator = _operator;
  68784. _this.exposureAdjustment = exposureAdjustment;
  68785. var defines = "#define ";
  68786. if (_this._operator === TonemappingOperator.Hable)
  68787. defines += "HABLE_TONEMAPPING";
  68788. else if (_this._operator === TonemappingOperator.Reinhard)
  68789. defines += "REINHARD_TONEMAPPING";
  68790. else if (_this._operator === TonemappingOperator.HejiDawson)
  68791. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  68792. else if (_this._operator === TonemappingOperator.Photographic)
  68793. defines += "PHOTOGRAPHIC_TONEMAPPING";
  68794. //sadly a second call to create the effect.
  68795. _this.updateEffect(defines);
  68796. _this.onApply = function (effect) {
  68797. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  68798. };
  68799. return _this;
  68800. }
  68801. return TonemapPostProcess;
  68802. }(BABYLON.PostProcess));
  68803. BABYLON.TonemapPostProcess = TonemapPostProcess;
  68804. })(BABYLON || (BABYLON = {}));
  68805. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  68806. var BABYLON;
  68807. (function (BABYLON) {
  68808. var DisplayPassPostProcess = /** @class */ (function (_super) {
  68809. __extends(DisplayPassPostProcess, _super);
  68810. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  68811. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  68812. }
  68813. return DisplayPassPostProcess;
  68814. }(BABYLON.PostProcess));
  68815. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  68816. })(BABYLON || (BABYLON = {}));
  68817. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  68818. var BABYLON;
  68819. (function (BABYLON) {
  68820. var HighlightsPostProcess = /** @class */ (function (_super) {
  68821. __extends(HighlightsPostProcess, _super);
  68822. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68823. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68824. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68825. }
  68826. return HighlightsPostProcess;
  68827. }(BABYLON.PostProcess));
  68828. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  68831. var BABYLON;
  68832. (function (BABYLON) {
  68833. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  68834. __extends(ImageProcessingPostProcess, _super);
  68835. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  68836. if (camera === void 0) { camera = null; }
  68837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68838. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  68839. _this._fromLinearSpace = true;
  68840. /**
  68841. * Defines cache preventing GC.
  68842. */
  68843. _this._defines = {
  68844. IMAGEPROCESSING: false,
  68845. VIGNETTE: false,
  68846. VIGNETTEBLENDMODEMULTIPLY: false,
  68847. VIGNETTEBLENDMODEOPAQUE: false,
  68848. TONEMAPPING: false,
  68849. CONTRAST: false,
  68850. COLORCURVES: false,
  68851. COLORGRADING: false,
  68852. COLORGRADING3D: false,
  68853. FROMLINEARSPACE: false,
  68854. SAMPLER3DGREENDEPTH: false,
  68855. SAMPLER3DBGRMAP: false,
  68856. IMAGEPROCESSINGPOSTPROCESS: false,
  68857. EXPOSURE: false,
  68858. };
  68859. // Setup the configuration as forced by the constructor. This would then not force the
  68860. // scene materials output in linear space and let untouched the default forward pass.
  68861. if (imageProcessingConfiguration) {
  68862. imageProcessingConfiguration.applyByPostProcess = true;
  68863. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68864. // This will cause the shader to be compiled
  68865. _this.fromLinearSpace = false;
  68866. }
  68867. else {
  68868. _this._attachImageProcessingConfiguration(null, true);
  68869. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68870. }
  68871. _this.onApply = function (effect) {
  68872. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68873. };
  68874. return _this;
  68875. }
  68876. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68877. /**
  68878. * Gets the image processing configuration used either in this material.
  68879. */
  68880. get: function () {
  68881. return this._imageProcessingConfiguration;
  68882. },
  68883. /**
  68884. * Sets the Default image processing configuration used either in the this material.
  68885. *
  68886. * If sets to null, the scene one is in use.
  68887. */
  68888. set: function (value) {
  68889. this._attachImageProcessingConfiguration(value);
  68890. },
  68891. enumerable: true,
  68892. configurable: true
  68893. });
  68894. /**
  68895. * Attaches a new image processing configuration to the PBR Material.
  68896. * @param configuration
  68897. */
  68898. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68899. var _this = this;
  68900. if (doNotBuild === void 0) { doNotBuild = false; }
  68901. if (configuration === this._imageProcessingConfiguration) {
  68902. return;
  68903. }
  68904. // Detaches observer.
  68905. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68906. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68907. }
  68908. // Pick the scene configuration if needed.
  68909. if (!configuration) {
  68910. var scene = null;
  68911. var engine = this.getEngine();
  68912. var camera = this.getCamera();
  68913. if (camera) {
  68914. scene = camera.getScene();
  68915. }
  68916. else if (engine && engine.scenes) {
  68917. var scenes = engine.scenes;
  68918. scene = scenes[scenes.length - 1];
  68919. }
  68920. else {
  68921. scene = BABYLON.Engine.LastCreatedScene;
  68922. }
  68923. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68924. }
  68925. else {
  68926. this._imageProcessingConfiguration = configuration;
  68927. }
  68928. // Attaches observer.
  68929. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68930. _this._updateParameters();
  68931. });
  68932. // Ensure the effect will be rebuilt.
  68933. if (!doNotBuild) {
  68934. this._updateParameters();
  68935. }
  68936. };
  68937. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68938. /**
  68939. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68940. */
  68941. get: function () {
  68942. return this.imageProcessingConfiguration.colorCurves;
  68943. },
  68944. /**
  68945. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68946. */
  68947. set: function (value) {
  68948. this.imageProcessingConfiguration.colorCurves = value;
  68949. },
  68950. enumerable: true,
  68951. configurable: true
  68952. });
  68953. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68954. /**
  68955. * Gets wether the color curves effect is enabled.
  68956. */
  68957. get: function () {
  68958. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68959. },
  68960. /**
  68961. * Sets wether the color curves effect is enabled.
  68962. */
  68963. set: function (value) {
  68964. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68965. },
  68966. enumerable: true,
  68967. configurable: true
  68968. });
  68969. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68970. /**
  68971. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68972. */
  68973. get: function () {
  68974. return this.imageProcessingConfiguration.colorGradingTexture;
  68975. },
  68976. /**
  68977. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68978. */
  68979. set: function (value) {
  68980. this.imageProcessingConfiguration.colorGradingTexture = value;
  68981. },
  68982. enumerable: true,
  68983. configurable: true
  68984. });
  68985. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68986. /**
  68987. * Gets wether the color grading effect is enabled.
  68988. */
  68989. get: function () {
  68990. return this.imageProcessingConfiguration.colorGradingEnabled;
  68991. },
  68992. /**
  68993. * Gets wether the color grading effect is enabled.
  68994. */
  68995. set: function (value) {
  68996. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68997. },
  68998. enumerable: true,
  68999. configurable: true
  69000. });
  69001. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69002. /**
  69003. * Gets exposure used in the effect.
  69004. */
  69005. get: function () {
  69006. return this.imageProcessingConfiguration.exposure;
  69007. },
  69008. /**
  69009. * Sets exposure used in the effect.
  69010. */
  69011. set: function (value) {
  69012. this.imageProcessingConfiguration.exposure = value;
  69013. },
  69014. enumerable: true,
  69015. configurable: true
  69016. });
  69017. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69018. /**
  69019. * Gets wether tonemapping is enabled or not.
  69020. */
  69021. get: function () {
  69022. return this._imageProcessingConfiguration.toneMappingEnabled;
  69023. },
  69024. /**
  69025. * Sets wether tonemapping is enabled or not
  69026. */
  69027. set: function (value) {
  69028. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69029. },
  69030. enumerable: true,
  69031. configurable: true
  69032. });
  69033. ;
  69034. ;
  69035. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69036. /**
  69037. * Gets contrast used in the effect.
  69038. */
  69039. get: function () {
  69040. return this.imageProcessingConfiguration.contrast;
  69041. },
  69042. /**
  69043. * Sets contrast used in the effect.
  69044. */
  69045. set: function (value) {
  69046. this.imageProcessingConfiguration.contrast = value;
  69047. },
  69048. enumerable: true,
  69049. configurable: true
  69050. });
  69051. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69052. /**
  69053. * Gets Vignette stretch size.
  69054. */
  69055. get: function () {
  69056. return this.imageProcessingConfiguration.vignetteStretch;
  69057. },
  69058. /**
  69059. * Sets Vignette stretch size.
  69060. */
  69061. set: function (value) {
  69062. this.imageProcessingConfiguration.vignetteStretch = value;
  69063. },
  69064. enumerable: true,
  69065. configurable: true
  69066. });
  69067. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69068. /**
  69069. * Gets Vignette centre X Offset.
  69070. */
  69071. get: function () {
  69072. return this.imageProcessingConfiguration.vignetteCentreX;
  69073. },
  69074. /**
  69075. * Sets Vignette centre X Offset.
  69076. */
  69077. set: function (value) {
  69078. this.imageProcessingConfiguration.vignetteCentreX = value;
  69079. },
  69080. enumerable: true,
  69081. configurable: true
  69082. });
  69083. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69084. /**
  69085. * Gets Vignette centre Y Offset.
  69086. */
  69087. get: function () {
  69088. return this.imageProcessingConfiguration.vignetteCentreY;
  69089. },
  69090. /**
  69091. * Sets Vignette centre Y Offset.
  69092. */
  69093. set: function (value) {
  69094. this.imageProcessingConfiguration.vignetteCentreY = value;
  69095. },
  69096. enumerable: true,
  69097. configurable: true
  69098. });
  69099. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69100. /**
  69101. * Gets Vignette weight or intensity of the vignette effect.
  69102. */
  69103. get: function () {
  69104. return this.imageProcessingConfiguration.vignetteWeight;
  69105. },
  69106. /**
  69107. * Sets Vignette weight or intensity of the vignette effect.
  69108. */
  69109. set: function (value) {
  69110. this.imageProcessingConfiguration.vignetteWeight = value;
  69111. },
  69112. enumerable: true,
  69113. configurable: true
  69114. });
  69115. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69116. /**
  69117. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69118. * if vignetteEnabled is set to true.
  69119. */
  69120. get: function () {
  69121. return this.imageProcessingConfiguration.vignetteColor;
  69122. },
  69123. /**
  69124. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69125. * if vignetteEnabled is set to true.
  69126. */
  69127. set: function (value) {
  69128. this.imageProcessingConfiguration.vignetteColor = value;
  69129. },
  69130. enumerable: true,
  69131. configurable: true
  69132. });
  69133. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69134. /**
  69135. * Gets Camera field of view used by the Vignette effect.
  69136. */
  69137. get: function () {
  69138. return this.imageProcessingConfiguration.vignetteCameraFov;
  69139. },
  69140. /**
  69141. * Sets Camera field of view used by the Vignette effect.
  69142. */
  69143. set: function (value) {
  69144. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69145. },
  69146. enumerable: true,
  69147. configurable: true
  69148. });
  69149. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69150. /**
  69151. * Gets the vignette blend mode allowing different kind of effect.
  69152. */
  69153. get: function () {
  69154. return this.imageProcessingConfiguration.vignetteBlendMode;
  69155. },
  69156. /**
  69157. * Sets the vignette blend mode allowing different kind of effect.
  69158. */
  69159. set: function (value) {
  69160. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69161. },
  69162. enumerable: true,
  69163. configurable: true
  69164. });
  69165. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69166. /**
  69167. * Gets wether the vignette effect is enabled.
  69168. */
  69169. get: function () {
  69170. return this.imageProcessingConfiguration.vignetteEnabled;
  69171. },
  69172. /**
  69173. * Sets wether the vignette effect is enabled.
  69174. */
  69175. set: function (value) {
  69176. this.imageProcessingConfiguration.vignetteEnabled = value;
  69177. },
  69178. enumerable: true,
  69179. configurable: true
  69180. });
  69181. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69182. /**
  69183. * Gets wether the input of the processing is in Gamma or Linear Space.
  69184. */
  69185. get: function () {
  69186. return this._fromLinearSpace;
  69187. },
  69188. /**
  69189. * Sets wether the input of the processing is in Gamma or Linear Space.
  69190. */
  69191. set: function (value) {
  69192. if (this._fromLinearSpace === value) {
  69193. return;
  69194. }
  69195. this._fromLinearSpace = value;
  69196. this._updateParameters();
  69197. },
  69198. enumerable: true,
  69199. configurable: true
  69200. });
  69201. ImageProcessingPostProcess.prototype.getClassName = function () {
  69202. return "ImageProcessingPostProcess";
  69203. };
  69204. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69205. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69206. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69207. var defines = "";
  69208. for (var define in this._defines) {
  69209. if (this._defines[define]) {
  69210. defines += "#define " + define + ";\r\n";
  69211. }
  69212. }
  69213. var samplers = ["textureSampler"];
  69214. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69215. var uniforms = ["scale"];
  69216. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69217. this.updateEffect(defines, uniforms, samplers);
  69218. };
  69219. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69220. _super.prototype.dispose.call(this, camera);
  69221. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69222. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69223. }
  69224. this.imageProcessingConfiguration.applyByPostProcess = false;
  69225. };
  69226. __decorate([
  69227. BABYLON.serialize()
  69228. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69229. return ImageProcessingPostProcess;
  69230. }(BABYLON.PostProcess));
  69231. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69232. })(BABYLON || (BABYLON = {}));
  69233. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69234. var BABYLON;
  69235. (function (BABYLON) {
  69236. /**
  69237. * The Blur Post Process which blurs an image based on a kernel and direction.
  69238. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69239. */
  69240. var BlurPostProcess = /** @class */ (function (_super) {
  69241. __extends(BlurPostProcess, _super);
  69242. /**
  69243. * Creates a new instance of @see BlurPostProcess
  69244. * @param name The name of the effect.
  69245. * @param direction The direction in which to blur the image.
  69246. * @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.
  69247. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69248. * @param camera The camera to apply the render pass to.
  69249. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69250. * @param engine The engine which the post process will be applied. (default: current engine)
  69251. * @param reusable If the post process can be reused on the same frame. (default: false)
  69252. * @param textureType Type of textures used when performing the post process. (default: 0)
  69253. */
  69254. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69256. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69257. if (defines === void 0) { defines = ""; }
  69258. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  69259. _this.direction = direction;
  69260. _this._packedFloat = false;
  69261. _this._staticDefines = "";
  69262. _this._staticDefines = defines;
  69263. _this.onApplyObservable.add(function (effect) {
  69264. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69265. });
  69266. _this.kernel = kernel;
  69267. return _this;
  69268. }
  69269. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69270. /**
  69271. * Gets the length in pixels of the blur sample region
  69272. */
  69273. get: function () {
  69274. return this._idealKernel;
  69275. },
  69276. /**
  69277. * Sets the length in pixels of the blur sample region
  69278. */
  69279. set: function (v) {
  69280. if (this._idealKernel === v) {
  69281. return;
  69282. }
  69283. v = Math.max(v, 1);
  69284. this._idealKernel = v;
  69285. this._kernel = this._nearestBestKernel(v);
  69286. this._updateParameters();
  69287. },
  69288. enumerable: true,
  69289. configurable: true
  69290. });
  69291. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69292. /**
  69293. * Gets wether or not the blur is unpacking/repacking floats
  69294. */
  69295. get: function () {
  69296. return this._packedFloat;
  69297. },
  69298. /**
  69299. * Sets wether or not the blur needs to unpack/repack floats
  69300. */
  69301. set: function (v) {
  69302. if (this._packedFloat === v) {
  69303. return;
  69304. }
  69305. this._packedFloat = v;
  69306. this._updateParameters();
  69307. },
  69308. enumerable: true,
  69309. configurable: true
  69310. });
  69311. BlurPostProcess.prototype._updateParameters = function () {
  69312. // Generate sampling offsets and weights
  69313. var N = this._kernel;
  69314. var centerIndex = (N - 1) / 2;
  69315. // Generate Gaussian sampling weights over kernel
  69316. var offsets = [];
  69317. var weights = [];
  69318. var totalWeight = 0;
  69319. for (var i = 0; i < N; i++) {
  69320. var u = i / (N - 1);
  69321. var w = this._gaussianWeight(u * 2.0 - 1);
  69322. offsets[i] = (i - centerIndex);
  69323. weights[i] = w;
  69324. totalWeight += w;
  69325. }
  69326. // Normalize weights
  69327. for (var i = 0; i < weights.length; i++) {
  69328. weights[i] /= totalWeight;
  69329. }
  69330. // Optimize: combine samples to take advantage of hardware linear sampling
  69331. // Walk from left to center, combining pairs (symmetrically)
  69332. var linearSamplingWeights = [];
  69333. var linearSamplingOffsets = [];
  69334. var linearSamplingMap = [];
  69335. for (var i = 0; i <= centerIndex; i += 2) {
  69336. var j = Math.min(i + 1, Math.floor(centerIndex));
  69337. var singleCenterSample = i === j;
  69338. if (singleCenterSample) {
  69339. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69340. }
  69341. else {
  69342. var sharedCell = j === centerIndex;
  69343. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69344. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69345. if (offsetLinear === 0) {
  69346. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69347. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69348. }
  69349. else {
  69350. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69351. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69352. }
  69353. }
  69354. }
  69355. for (var i = 0; i < linearSamplingMap.length; i++) {
  69356. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69357. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69358. }
  69359. // Replace with optimized
  69360. offsets = linearSamplingOffsets;
  69361. weights = linearSamplingWeights;
  69362. // Generate shaders
  69363. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69364. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69365. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69366. var defines = "";
  69367. defines += this._staticDefines;
  69368. for (var i = 0; i < varyingCount; i++) {
  69369. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69370. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69371. }
  69372. var depCount = 0;
  69373. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69374. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69375. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69376. depCount++;
  69377. }
  69378. if (this.packedFloat) {
  69379. defines += "#define PACKEDFLOAT 1";
  69380. }
  69381. this.updateEffect(defines, null, null, {
  69382. varyingCount: varyingCount,
  69383. depCount: depCount
  69384. });
  69385. };
  69386. /**
  69387. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69388. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69389. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69390. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69391. * The gaps between physical kernels are compensated for in the weighting of the samples
  69392. * @param idealKernel Ideal blur kernel.
  69393. * @return Nearest best kernel.
  69394. */
  69395. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69396. var v = Math.round(idealKernel);
  69397. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69398. var k = _a[_i];
  69399. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69400. return Math.max(k, 3);
  69401. }
  69402. }
  69403. return Math.max(v, 3);
  69404. };
  69405. /**
  69406. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69407. * @param x The point on the Gaussian distribution to sample.
  69408. * @return the value of the Gaussian function at x.
  69409. */
  69410. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69411. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69412. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69413. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69414. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69415. // truncated at around 1.3% of peak strength.
  69416. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69417. var sigma = (1 / 3);
  69418. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69419. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69420. var weight = (1.0 / denominator) * Math.exp(exponent);
  69421. return weight;
  69422. };
  69423. /**
  69424. * Generates a string that can be used as a floating point number in GLSL.
  69425. * @param x Value to print.
  69426. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69427. * @return GLSL float string.
  69428. */
  69429. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69430. if (decimalFigures === void 0) { decimalFigures = 8; }
  69431. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69432. };
  69433. return BlurPostProcess;
  69434. }(BABYLON.PostProcess));
  69435. BABYLON.BlurPostProcess = BlurPostProcess;
  69436. })(BABYLON || (BABYLON = {}));
  69437. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69438. var BABYLON;
  69439. (function (BABYLON) {
  69440. var Bone = /** @class */ (function (_super) {
  69441. __extends(Bone, _super);
  69442. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69443. if (parentBone === void 0) { parentBone = null; }
  69444. if (localMatrix === void 0) { localMatrix = null; }
  69445. if (restPose === void 0) { restPose = null; }
  69446. if (baseMatrix === void 0) { baseMatrix = null; }
  69447. if (index === void 0) { index = null; }
  69448. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69449. _this.name = name;
  69450. _this.children = new Array();
  69451. _this.animations = new Array();
  69452. // Set this value to map this bone to a different index in the transform matrices.
  69453. // Set this value to -1 to exclude the bone from the transform matrices.
  69454. _this._index = null;
  69455. _this._worldTransform = new BABYLON.Matrix();
  69456. _this._absoluteTransform = new BABYLON.Matrix();
  69457. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69458. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69459. _this._scaleVector = BABYLON.Vector3.One();
  69460. _this._negateScaleChildren = BABYLON.Vector3.One();
  69461. _this._scalingDeterminant = 1;
  69462. _this._skeleton = skeleton;
  69463. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69464. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69465. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69466. _this._index = index;
  69467. skeleton.bones.push(_this);
  69468. _this.setParent(parentBone, false);
  69469. _this._updateDifferenceMatrix();
  69470. return _this;
  69471. }
  69472. Object.defineProperty(Bone.prototype, "_matrix", {
  69473. get: function () {
  69474. return this._localMatrix;
  69475. },
  69476. set: function (val) {
  69477. if (this._localMatrix) {
  69478. this._localMatrix.copyFrom(val);
  69479. }
  69480. else {
  69481. this._localMatrix = val;
  69482. }
  69483. },
  69484. enumerable: true,
  69485. configurable: true
  69486. });
  69487. // Members
  69488. Bone.prototype.getSkeleton = function () {
  69489. return this._skeleton;
  69490. };
  69491. Bone.prototype.getParent = function () {
  69492. return this._parent;
  69493. };
  69494. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69495. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69496. if (this._parent === parent) {
  69497. return;
  69498. }
  69499. if (this._parent) {
  69500. var index = this._parent.children.indexOf(this);
  69501. if (index !== -1) {
  69502. this._parent.children.splice(index, 1);
  69503. }
  69504. }
  69505. this._parent = parent;
  69506. if (this._parent) {
  69507. this._parent.children.push(this);
  69508. }
  69509. if (updateDifferenceMatrix) {
  69510. this._updateDifferenceMatrix();
  69511. }
  69512. };
  69513. Bone.prototype.getLocalMatrix = function () {
  69514. return this._localMatrix;
  69515. };
  69516. Bone.prototype.getBaseMatrix = function () {
  69517. return this._baseMatrix;
  69518. };
  69519. Bone.prototype.getRestPose = function () {
  69520. return this._restPose;
  69521. };
  69522. Bone.prototype.returnToRest = function () {
  69523. this.updateMatrix(this._restPose.clone());
  69524. };
  69525. Bone.prototype.getWorldMatrix = function () {
  69526. return this._worldTransform;
  69527. };
  69528. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69529. return this._invertedAbsoluteTransform;
  69530. };
  69531. Bone.prototype.getAbsoluteTransform = function () {
  69532. return this._absoluteTransform;
  69533. };
  69534. Object.defineProperty(Bone.prototype, "position", {
  69535. // Properties (matches AbstractMesh properties)
  69536. get: function () {
  69537. return this.getPosition();
  69538. },
  69539. set: function (newPosition) {
  69540. this.setPosition(newPosition);
  69541. },
  69542. enumerable: true,
  69543. configurable: true
  69544. });
  69545. Object.defineProperty(Bone.prototype, "rotation", {
  69546. get: function () {
  69547. return this.getRotation();
  69548. },
  69549. set: function (newRotation) {
  69550. this.setRotation(newRotation);
  69551. },
  69552. enumerable: true,
  69553. configurable: true
  69554. });
  69555. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69556. get: function () {
  69557. return this.getRotationQuaternion();
  69558. },
  69559. set: function (newRotation) {
  69560. this.setRotationQuaternion(newRotation);
  69561. },
  69562. enumerable: true,
  69563. configurable: true
  69564. });
  69565. Object.defineProperty(Bone.prototype, "scaling", {
  69566. get: function () {
  69567. return this.getScale();
  69568. },
  69569. set: function (newScaling) {
  69570. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69571. },
  69572. enumerable: true,
  69573. configurable: true
  69574. });
  69575. // Methods
  69576. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69577. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69578. this._baseMatrix = matrix.clone();
  69579. this._localMatrix = matrix.clone();
  69580. this._skeleton._markAsDirty();
  69581. if (updateDifferenceMatrix) {
  69582. this._updateDifferenceMatrix();
  69583. }
  69584. };
  69585. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69586. if (!rootMatrix) {
  69587. rootMatrix = this._baseMatrix;
  69588. }
  69589. if (this._parent) {
  69590. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69591. }
  69592. else {
  69593. this._absoluteTransform.copyFrom(rootMatrix);
  69594. }
  69595. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69596. for (var index = 0; index < this.children.length; index++) {
  69597. this.children[index]._updateDifferenceMatrix();
  69598. }
  69599. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69600. };
  69601. Bone.prototype.markAsDirty = function () {
  69602. this._currentRenderId++;
  69603. this._skeleton._markAsDirty();
  69604. };
  69605. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69606. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69607. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69608. // all animation may be coming from a library skeleton, so may need to create animation
  69609. if (this.animations.length === 0) {
  69610. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69611. this.animations[0].setKeys([]);
  69612. }
  69613. // get animation info / verify there is such a range from the source bone
  69614. var sourceRange = source.animations[0].getRange(rangeName);
  69615. if (!sourceRange) {
  69616. return false;
  69617. }
  69618. var from = sourceRange.from;
  69619. var to = sourceRange.to;
  69620. var sourceKeys = source.animations[0].getKeys();
  69621. // rescaling prep
  69622. var sourceBoneLength = source.length;
  69623. var sourceParent = source.getParent();
  69624. var parent = this.getParent();
  69625. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69626. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69627. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69628. var destKeys = this.animations[0].getKeys();
  69629. // loop vars declaration
  69630. var orig;
  69631. var origTranslation;
  69632. var mat;
  69633. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69634. orig = sourceKeys[key];
  69635. if (orig.frame >= from && orig.frame <= to) {
  69636. if (rescaleAsRequired) {
  69637. mat = orig.value.clone();
  69638. // scale based on parent ratio, when bone has parent
  69639. if (parentScalingReqd) {
  69640. origTranslation = mat.getTranslation();
  69641. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69642. // scale based on skeleton dimension ratio when root bone, and value is passed
  69643. }
  69644. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69645. origTranslation = mat.getTranslation();
  69646. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69647. // use original when root bone, and no data for skelDimensionsRatio
  69648. }
  69649. else {
  69650. mat = orig.value;
  69651. }
  69652. }
  69653. else {
  69654. mat = orig.value;
  69655. }
  69656. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69657. }
  69658. }
  69659. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69660. return true;
  69661. };
  69662. /**
  69663. * Translate the bone in local or world space.
  69664. * @param vec The amount to translate the bone.
  69665. * @param space The space that the translation is in.
  69666. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69667. */
  69668. Bone.prototype.translate = function (vec, space, mesh) {
  69669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69670. var lm = this.getLocalMatrix();
  69671. if (space == BABYLON.Space.LOCAL) {
  69672. lm.m[12] += vec.x;
  69673. lm.m[13] += vec.y;
  69674. lm.m[14] += vec.z;
  69675. }
  69676. else {
  69677. var wm = null;
  69678. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69679. if (mesh) {
  69680. wm = mesh.getWorldMatrix();
  69681. }
  69682. this._skeleton.computeAbsoluteTransforms();
  69683. var tmat = Bone._tmpMats[0];
  69684. var tvec = Bone._tmpVecs[0];
  69685. if (this._parent) {
  69686. if (mesh && wm) {
  69687. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69688. tmat.multiplyToRef(wm, tmat);
  69689. }
  69690. else {
  69691. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69692. }
  69693. }
  69694. tmat.m[12] = 0;
  69695. tmat.m[13] = 0;
  69696. tmat.m[14] = 0;
  69697. tmat.invert();
  69698. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  69699. lm.m[12] += tvec.x;
  69700. lm.m[13] += tvec.y;
  69701. lm.m[14] += tvec.z;
  69702. }
  69703. this.markAsDirty();
  69704. };
  69705. /**
  69706. * Set the postion of the bone in local or world space.
  69707. * @param position The position to set the bone.
  69708. * @param space The space that the position is in.
  69709. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69710. */
  69711. Bone.prototype.setPosition = function (position, space, mesh) {
  69712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69713. var lm = this.getLocalMatrix();
  69714. if (space == BABYLON.Space.LOCAL) {
  69715. lm.m[12] = position.x;
  69716. lm.m[13] = position.y;
  69717. lm.m[14] = position.z;
  69718. }
  69719. else {
  69720. var wm = null;
  69721. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69722. if (mesh) {
  69723. wm = mesh.getWorldMatrix();
  69724. }
  69725. this._skeleton.computeAbsoluteTransforms();
  69726. var tmat = Bone._tmpMats[0];
  69727. var vec = Bone._tmpVecs[0];
  69728. if (this._parent) {
  69729. if (mesh && wm) {
  69730. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69731. tmat.multiplyToRef(wm, tmat);
  69732. }
  69733. else {
  69734. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69735. }
  69736. }
  69737. tmat.invert();
  69738. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  69739. lm.m[12] = vec.x;
  69740. lm.m[13] = vec.y;
  69741. lm.m[14] = vec.z;
  69742. }
  69743. this.markAsDirty();
  69744. };
  69745. /**
  69746. * Set the absolute postion of the bone (world space).
  69747. * @param position The position to set the bone.
  69748. * @param mesh The mesh that this bone is attached to.
  69749. */
  69750. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  69751. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  69752. };
  69753. /**
  69754. * Set the scale of the bone on the x, y and z axes.
  69755. * @param x The scale of the bone on the x axis.
  69756. * @param x The scale of the bone on the y axis.
  69757. * @param z The scale of the bone on the z axis.
  69758. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69759. */
  69760. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  69761. if (scaleChildren === void 0) { scaleChildren = false; }
  69762. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  69763. if (!scaleChildren) {
  69764. this._negateScaleChildren.x = 1 / x;
  69765. this._negateScaleChildren.y = 1 / y;
  69766. this._negateScaleChildren.z = 1 / z;
  69767. }
  69768. this._syncScaleVector();
  69769. }
  69770. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  69771. };
  69772. /**
  69773. * Scale the bone on the x, y and z axes.
  69774. * @param x The amount to scale the bone on the x axis.
  69775. * @param x The amount to scale the bone on the y axis.
  69776. * @param z The amount to scale the bone on the z axis.
  69777. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69778. */
  69779. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  69780. if (scaleChildren === void 0) { scaleChildren = false; }
  69781. var locMat = this.getLocalMatrix();
  69782. var origLocMat = Bone._tmpMats[0];
  69783. origLocMat.copyFrom(locMat);
  69784. var origLocMatInv = Bone._tmpMats[1];
  69785. origLocMatInv.copyFrom(origLocMat);
  69786. origLocMatInv.invert();
  69787. var scaleMat = Bone._tmpMats[2];
  69788. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  69789. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  69790. this._scaleVector.x *= x;
  69791. this._scaleVector.y *= y;
  69792. this._scaleVector.z *= z;
  69793. locMat.multiplyToRef(origLocMatInv, locMat);
  69794. locMat.multiplyToRef(scaleMat, locMat);
  69795. locMat.multiplyToRef(origLocMat, locMat);
  69796. var parent = this.getParent();
  69797. if (parent) {
  69798. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  69799. }
  69800. else {
  69801. this.getAbsoluteTransform().copyFrom(locMat);
  69802. }
  69803. var len = this.children.length;
  69804. scaleMat.invert();
  69805. for (var i = 0; i < len; i++) {
  69806. var child = this.children[i];
  69807. var cm = child.getLocalMatrix();
  69808. cm.multiplyToRef(scaleMat, cm);
  69809. var lm = child.getLocalMatrix();
  69810. lm.m[12] *= x;
  69811. lm.m[13] *= y;
  69812. lm.m[14] *= z;
  69813. }
  69814. this.computeAbsoluteTransforms();
  69815. if (scaleChildren) {
  69816. for (var i = 0; i < len; i++) {
  69817. this.children[i].scale(x, y, z, scaleChildren);
  69818. }
  69819. }
  69820. this.markAsDirty();
  69821. };
  69822. /**
  69823. * Set the yaw, pitch, and roll of the bone in local or world space.
  69824. * @param yaw The rotation of the bone on the y axis.
  69825. * @param pitch The rotation of the bone on the x axis.
  69826. * @param roll The rotation of the bone on the z axis.
  69827. * @param space The space that the axes of rotation are in.
  69828. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69829. */
  69830. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69832. var rotMat = Bone._tmpMats[0];
  69833. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69834. var rotMatInv = Bone._tmpMats[1];
  69835. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69836. rotMatInv.multiplyToRef(rotMat, rotMat);
  69837. this._rotateWithMatrix(rotMat, space, mesh);
  69838. };
  69839. /**
  69840. * Rotate the bone on an axis in local or world space.
  69841. * @param axis The axis to rotate the bone on.
  69842. * @param amount The amount to rotate the bone.
  69843. * @param space The space that the axis is in.
  69844. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69845. */
  69846. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69847. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69848. var rmat = Bone._tmpMats[0];
  69849. rmat.m[12] = 0;
  69850. rmat.m[13] = 0;
  69851. rmat.m[14] = 0;
  69852. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69853. this._rotateWithMatrix(rmat, space, mesh);
  69854. };
  69855. /**
  69856. * Set the rotation of the bone to a particular axis angle in local or world space.
  69857. * @param axis The axis to rotate the bone on.
  69858. * @param angle The angle that the bone should be rotated to.
  69859. * @param space The space that the axis is in.
  69860. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69861. */
  69862. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69863. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69864. var rotMat = Bone._tmpMats[0];
  69865. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69866. var rotMatInv = Bone._tmpMats[1];
  69867. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69868. rotMatInv.multiplyToRef(rotMat, rotMat);
  69869. this._rotateWithMatrix(rotMat, space, mesh);
  69870. };
  69871. /**
  69872. * Set the euler rotation of the bone in local of world space.
  69873. * @param rotation The euler rotation that the bone should be set to.
  69874. * @param space The space that the rotation is in.
  69875. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69876. */
  69877. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69879. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69880. };
  69881. /**
  69882. * Set the quaternion rotation of the bone in local of world space.
  69883. * @param quat The quaternion rotation that the bone should be set to.
  69884. * @param space The space that the rotation is in.
  69885. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69886. */
  69887. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69889. var rotMatInv = Bone._tmpMats[0];
  69890. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69891. var rotMat = Bone._tmpMats[1];
  69892. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69893. rotMatInv.multiplyToRef(rotMat, rotMat);
  69894. this._rotateWithMatrix(rotMat, space, mesh);
  69895. };
  69896. /**
  69897. * Set the rotation matrix of the bone in local of world space.
  69898. * @param rotMat The rotation matrix that the bone should be set to.
  69899. * @param space The space that the rotation is in.
  69900. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69901. */
  69902. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69904. var rotMatInv = Bone._tmpMats[0];
  69905. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69906. var rotMat2 = Bone._tmpMats[1];
  69907. rotMat2.copyFrom(rotMat);
  69908. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69909. this._rotateWithMatrix(rotMat2, space, mesh);
  69910. };
  69911. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69913. var lmat = this.getLocalMatrix();
  69914. var lx = lmat.m[12];
  69915. var ly = lmat.m[13];
  69916. var lz = lmat.m[14];
  69917. var parent = this.getParent();
  69918. var parentScale = Bone._tmpMats[3];
  69919. var parentScaleInv = Bone._tmpMats[4];
  69920. if (parent) {
  69921. if (space == BABYLON.Space.WORLD) {
  69922. if (mesh) {
  69923. parentScale.copyFrom(mesh.getWorldMatrix());
  69924. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69925. }
  69926. else {
  69927. parentScale.copyFrom(parent.getAbsoluteTransform());
  69928. }
  69929. }
  69930. else {
  69931. parentScale = parent._scaleMatrix;
  69932. }
  69933. parentScaleInv.copyFrom(parentScale);
  69934. parentScaleInv.invert();
  69935. lmat.multiplyToRef(parentScale, lmat);
  69936. lmat.multiplyToRef(rmat, lmat);
  69937. lmat.multiplyToRef(parentScaleInv, lmat);
  69938. }
  69939. else {
  69940. if (space == BABYLON.Space.WORLD && mesh) {
  69941. parentScale.copyFrom(mesh.getWorldMatrix());
  69942. parentScaleInv.copyFrom(parentScale);
  69943. parentScaleInv.invert();
  69944. lmat.multiplyToRef(parentScale, lmat);
  69945. lmat.multiplyToRef(rmat, lmat);
  69946. lmat.multiplyToRef(parentScaleInv, lmat);
  69947. }
  69948. else {
  69949. lmat.multiplyToRef(rmat, lmat);
  69950. }
  69951. }
  69952. lmat.m[12] = lx;
  69953. lmat.m[13] = ly;
  69954. lmat.m[14] = lz;
  69955. this.computeAbsoluteTransforms();
  69956. this.markAsDirty();
  69957. };
  69958. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69959. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69960. if (space == BABYLON.Space.WORLD) {
  69961. var scaleMatrix = Bone._tmpMats[2];
  69962. scaleMatrix.copyFrom(this._scaleMatrix);
  69963. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69964. if (mesh) {
  69965. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69966. var meshScale = Bone._tmpMats[3];
  69967. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69968. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69969. }
  69970. rotMatInv.invert();
  69971. scaleMatrix.m[0] *= this._scalingDeterminant;
  69972. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69973. }
  69974. else {
  69975. rotMatInv.copyFrom(this.getLocalMatrix());
  69976. rotMatInv.invert();
  69977. var scaleMatrix = Bone._tmpMats[2];
  69978. scaleMatrix.copyFrom(this._scaleMatrix);
  69979. if (this._parent) {
  69980. var pscaleMatrix = Bone._tmpMats[3];
  69981. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69982. pscaleMatrix.invert();
  69983. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69984. }
  69985. else {
  69986. scaleMatrix.m[0] *= this._scalingDeterminant;
  69987. }
  69988. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69989. }
  69990. };
  69991. /**
  69992. * Get the scale of the bone
  69993. * @returns the scale of the bone
  69994. */
  69995. Bone.prototype.getScale = function () {
  69996. return this._scaleVector.clone();
  69997. };
  69998. /**
  69999. * Copy the scale of the bone to a vector3.
  70000. * @param result The vector3 to copy the scale to
  70001. */
  70002. Bone.prototype.getScaleToRef = function (result) {
  70003. result.copyFrom(this._scaleVector);
  70004. };
  70005. /**
  70006. * Get the position of the bone in local or world space.
  70007. * @param space The space that the returned position is in.
  70008. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70009. * @returns The position of the bone
  70010. */
  70011. Bone.prototype.getPosition = function (space, mesh) {
  70012. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70013. if (mesh === void 0) { mesh = null; }
  70014. var pos = BABYLON.Vector3.Zero();
  70015. this.getPositionToRef(space, mesh, pos);
  70016. return pos;
  70017. };
  70018. /**
  70019. * Copy the position of the bone to a vector3 in local or world space.
  70020. * @param space The space that the returned position is in.
  70021. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70022. * @param result The vector3 to copy the position to.
  70023. */
  70024. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70025. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70026. if (space == BABYLON.Space.LOCAL) {
  70027. var lm = this.getLocalMatrix();
  70028. result.x = lm.m[12];
  70029. result.y = lm.m[13];
  70030. result.z = lm.m[14];
  70031. }
  70032. else {
  70033. var wm = null;
  70034. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70035. if (mesh) {
  70036. wm = mesh.getWorldMatrix();
  70037. }
  70038. this._skeleton.computeAbsoluteTransforms();
  70039. var tmat = Bone._tmpMats[0];
  70040. if (mesh && wm) {
  70041. tmat.copyFrom(this.getAbsoluteTransform());
  70042. tmat.multiplyToRef(wm, tmat);
  70043. }
  70044. else {
  70045. tmat = this.getAbsoluteTransform();
  70046. }
  70047. result.x = tmat.m[12];
  70048. result.y = tmat.m[13];
  70049. result.z = tmat.m[14];
  70050. }
  70051. };
  70052. /**
  70053. * Get the absolute position of the bone (world space).
  70054. * @param mesh The mesh that this bone is attached to.
  70055. * @returns The absolute position of the bone
  70056. */
  70057. Bone.prototype.getAbsolutePosition = function (mesh) {
  70058. if (mesh === void 0) { mesh = null; }
  70059. var pos = BABYLON.Vector3.Zero();
  70060. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70061. return pos;
  70062. };
  70063. /**
  70064. * Copy the absolute position of the bone (world space) to the result param.
  70065. * @param mesh The mesh that this bone is attached to.
  70066. * @param result The vector3 to copy the absolute position to.
  70067. */
  70068. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70069. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70070. };
  70071. /**
  70072. * Compute the absolute transforms of this bone and its children.
  70073. */
  70074. Bone.prototype.computeAbsoluteTransforms = function () {
  70075. if (this._parent) {
  70076. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70077. }
  70078. else {
  70079. this._absoluteTransform.copyFrom(this._localMatrix);
  70080. var poseMatrix = this._skeleton.getPoseMatrix();
  70081. if (poseMatrix) {
  70082. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70083. }
  70084. }
  70085. var children = this.children;
  70086. var len = children.length;
  70087. for (var i = 0; i < len; i++) {
  70088. children[i].computeAbsoluteTransforms();
  70089. }
  70090. };
  70091. Bone.prototype._syncScaleVector = function () {
  70092. var lm = this.getLocalMatrix();
  70093. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70094. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70095. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70096. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70097. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70098. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70099. this._scaleVector.x = xs * Math.sqrt(xsq);
  70100. this._scaleVector.y = ys * Math.sqrt(ysq);
  70101. this._scaleVector.z = zs * Math.sqrt(zsq);
  70102. if (this._parent) {
  70103. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70104. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70105. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70106. }
  70107. 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);
  70108. };
  70109. /**
  70110. * Get the world direction from an axis that is in the local space of the bone.
  70111. * @param localAxis The local direction that is used to compute the world direction.
  70112. * @param mesh The mesh that this bone is attached to.
  70113. * @returns The world direction
  70114. */
  70115. Bone.prototype.getDirection = function (localAxis, mesh) {
  70116. if (mesh === void 0) { mesh = null; }
  70117. var result = BABYLON.Vector3.Zero();
  70118. this.getDirectionToRef(localAxis, mesh, result);
  70119. return result;
  70120. };
  70121. /**
  70122. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70123. * @param localAxis The local direction that is used to compute the world direction.
  70124. * @param mesh The mesh that this bone is attached to.
  70125. * @param result The vector3 that the world direction will be copied to.
  70126. */
  70127. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70128. if (mesh === void 0) { mesh = null; }
  70129. var wm = null;
  70130. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70131. if (mesh) {
  70132. wm = mesh.getWorldMatrix();
  70133. }
  70134. this._skeleton.computeAbsoluteTransforms();
  70135. var mat = Bone._tmpMats[0];
  70136. mat.copyFrom(this.getAbsoluteTransform());
  70137. if (mesh && wm) {
  70138. mat.multiplyToRef(wm, mat);
  70139. }
  70140. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70141. result.normalize();
  70142. };
  70143. /**
  70144. * Get the euler rotation of the bone in local or world space.
  70145. * @param space The space that the rotation should be in.
  70146. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70147. * @returns The euler rotation
  70148. */
  70149. Bone.prototype.getRotation = function (space, mesh) {
  70150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70151. if (mesh === void 0) { mesh = null; }
  70152. var result = BABYLON.Vector3.Zero();
  70153. this.getRotationToRef(space, mesh, result);
  70154. return result;
  70155. };
  70156. /**
  70157. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70158. * @param space The space that the rotation should be in.
  70159. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70160. * @param result The vector3 that the rotation should be copied to.
  70161. */
  70162. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70163. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70164. if (mesh === void 0) { mesh = null; }
  70165. var quat = Bone._tmpQuat;
  70166. this.getRotationQuaternionToRef(space, mesh, quat);
  70167. quat.toEulerAnglesToRef(result);
  70168. };
  70169. /**
  70170. * Get the quaternion rotation of the bone in either local or world space.
  70171. * @param space The space that the rotation should be in.
  70172. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70173. * @returns The quaternion rotation
  70174. */
  70175. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70176. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70177. if (mesh === void 0) { mesh = null; }
  70178. var result = BABYLON.Quaternion.Identity();
  70179. this.getRotationQuaternionToRef(space, mesh, result);
  70180. return result;
  70181. };
  70182. /**
  70183. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70184. * @param space The space that the rotation should be in.
  70185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70186. * @param result The quaternion that the rotation should be copied to.
  70187. */
  70188. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70190. if (mesh === void 0) { mesh = null; }
  70191. if (space == BABYLON.Space.LOCAL) {
  70192. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70193. }
  70194. else {
  70195. var mat = Bone._tmpMats[0];
  70196. var amat = this.getAbsoluteTransform();
  70197. if (mesh) {
  70198. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70199. }
  70200. else {
  70201. mat.copyFrom(amat);
  70202. }
  70203. mat.m[0] *= this._scalingDeterminant;
  70204. mat.m[1] *= this._scalingDeterminant;
  70205. mat.m[2] *= this._scalingDeterminant;
  70206. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70207. }
  70208. };
  70209. /**
  70210. * Get the rotation matrix of the bone in local or world space.
  70211. * @param space The space that the rotation should be in.
  70212. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70213. * @returns The rotation matrix
  70214. */
  70215. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70217. var result = BABYLON.Matrix.Identity();
  70218. this.getRotationMatrixToRef(space, mesh, result);
  70219. return result;
  70220. };
  70221. /**
  70222. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70223. * @param space The space that the rotation should be in.
  70224. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70225. * @param result The quaternion that the rotation should be copied to.
  70226. */
  70227. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70229. if (space == BABYLON.Space.LOCAL) {
  70230. this.getLocalMatrix().getRotationMatrixToRef(result);
  70231. }
  70232. else {
  70233. var mat = Bone._tmpMats[0];
  70234. var amat = this.getAbsoluteTransform();
  70235. if (mesh) {
  70236. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70237. }
  70238. else {
  70239. mat.copyFrom(amat);
  70240. }
  70241. mat.m[0] *= this._scalingDeterminant;
  70242. mat.m[1] *= this._scalingDeterminant;
  70243. mat.m[2] *= this._scalingDeterminant;
  70244. mat.getRotationMatrixToRef(result);
  70245. }
  70246. };
  70247. /**
  70248. * Get the world position of a point that is in the local space of the bone.
  70249. * @param position The local position
  70250. * @param mesh The mesh that this bone is attached to.
  70251. * @returns The world position
  70252. */
  70253. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70254. if (mesh === void 0) { mesh = null; }
  70255. var result = BABYLON.Vector3.Zero();
  70256. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70257. return result;
  70258. };
  70259. /**
  70260. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70261. * @param position The local position
  70262. * @param mesh The mesh that this bone is attached to.
  70263. * @param result The vector3 that the world position should be copied to.
  70264. */
  70265. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70266. if (mesh === void 0) { mesh = null; }
  70267. var wm = null;
  70268. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70269. if (mesh) {
  70270. wm = mesh.getWorldMatrix();
  70271. }
  70272. this._skeleton.computeAbsoluteTransforms();
  70273. var tmat = Bone._tmpMats[0];
  70274. if (mesh && wm) {
  70275. tmat.copyFrom(this.getAbsoluteTransform());
  70276. tmat.multiplyToRef(wm, tmat);
  70277. }
  70278. else {
  70279. tmat = this.getAbsoluteTransform();
  70280. }
  70281. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70282. };
  70283. /**
  70284. * Get the local position of a point that is in world space.
  70285. * @param position The world position
  70286. * @param mesh The mesh that this bone is attached to.
  70287. * @returns The local position
  70288. */
  70289. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70290. if (mesh === void 0) { mesh = null; }
  70291. var result = BABYLON.Vector3.Zero();
  70292. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70293. return result;
  70294. };
  70295. /**
  70296. * Get the local position of a point that is in world space and copy it to the result param.
  70297. * @param position The world position
  70298. * @param mesh The mesh that this bone is attached to.
  70299. * @param result The vector3 that the local position should be copied to.
  70300. */
  70301. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70302. if (mesh === void 0) { mesh = null; }
  70303. var wm = null;
  70304. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70305. if (mesh) {
  70306. wm = mesh.getWorldMatrix();
  70307. }
  70308. this._skeleton.computeAbsoluteTransforms();
  70309. var tmat = Bone._tmpMats[0];
  70310. tmat.copyFrom(this.getAbsoluteTransform());
  70311. if (mesh && wm) {
  70312. tmat.multiplyToRef(wm, tmat);
  70313. }
  70314. tmat.invert();
  70315. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70316. };
  70317. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70318. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70319. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70320. return Bone;
  70321. }(BABYLON.Node));
  70322. BABYLON.Bone = Bone;
  70323. })(BABYLON || (BABYLON = {}));
  70324. //# sourceMappingURL=babylon.bone.js.map
  70325. var BABYLON;
  70326. (function (BABYLON) {
  70327. var BoneIKController = /** @class */ (function () {
  70328. function BoneIKController(mesh, bone, options) {
  70329. this.targetPosition = BABYLON.Vector3.Zero();
  70330. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70331. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70332. this.poleAngle = 0;
  70333. this.slerpAmount = 1;
  70334. this._bone1Quat = BABYLON.Quaternion.Identity();
  70335. this._bone1Mat = BABYLON.Matrix.Identity();
  70336. this._bone2Ang = Math.PI;
  70337. this._maxAngle = Math.PI;
  70338. this._rightHandedSystem = false;
  70339. this._bendAxis = BABYLON.Vector3.Right();
  70340. this._slerping = false;
  70341. this._adjustRoll = 0;
  70342. this._bone2 = bone;
  70343. this._bone1 = bone.getParent();
  70344. if (!this._bone1) {
  70345. return;
  70346. }
  70347. this.mesh = mesh;
  70348. var bonePos = bone.getPosition();
  70349. if (bone.getAbsoluteTransform().determinant() > 0) {
  70350. this._rightHandedSystem = true;
  70351. this._bendAxis.x = 0;
  70352. this._bendAxis.y = 0;
  70353. this._bendAxis.z = -1;
  70354. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70355. this._adjustRoll = Math.PI * .5;
  70356. this._bendAxis.z = 1;
  70357. }
  70358. }
  70359. if (this._bone1.length) {
  70360. var boneScale1 = this._bone1.getScale();
  70361. var boneScale2 = this._bone2.getScale();
  70362. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70363. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70364. }
  70365. else if (this._bone1.children[0]) {
  70366. mesh.computeWorldMatrix(true);
  70367. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70368. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70369. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70370. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70371. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70372. }
  70373. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70374. this.maxAngle = Math.PI;
  70375. if (options) {
  70376. if (options.targetMesh) {
  70377. this.targetMesh = options.targetMesh;
  70378. this.targetMesh.computeWorldMatrix(true);
  70379. }
  70380. if (options.poleTargetMesh) {
  70381. this.poleTargetMesh = options.poleTargetMesh;
  70382. this.poleTargetMesh.computeWorldMatrix(true);
  70383. }
  70384. else if (options.poleTargetBone) {
  70385. this.poleTargetBone = options.poleTargetBone;
  70386. }
  70387. else if (this._bone1.getParent()) {
  70388. this.poleTargetBone = this._bone1.getParent();
  70389. }
  70390. if (options.poleTargetLocalOffset) {
  70391. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70392. }
  70393. if (options.poleAngle) {
  70394. this.poleAngle = options.poleAngle;
  70395. }
  70396. if (options.bendAxis) {
  70397. this._bendAxis.copyFrom(options.bendAxis);
  70398. }
  70399. if (options.maxAngle) {
  70400. this.maxAngle = options.maxAngle;
  70401. }
  70402. if (options.slerpAmount) {
  70403. this.slerpAmount = options.slerpAmount;
  70404. }
  70405. }
  70406. }
  70407. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70408. get: function () {
  70409. return this._maxAngle;
  70410. },
  70411. set: function (value) {
  70412. this._setMaxAngle(value);
  70413. },
  70414. enumerable: true,
  70415. configurable: true
  70416. });
  70417. BoneIKController.prototype._setMaxAngle = function (ang) {
  70418. if (ang < 0) {
  70419. ang = 0;
  70420. }
  70421. if (ang > Math.PI || ang == undefined) {
  70422. ang = Math.PI;
  70423. }
  70424. this._maxAngle = ang;
  70425. var a = this._bone1Length;
  70426. var b = this._bone2Length;
  70427. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70428. };
  70429. BoneIKController.prototype.update = function () {
  70430. var bone1 = this._bone1;
  70431. if (!bone1) {
  70432. return;
  70433. }
  70434. var target = this.targetPosition;
  70435. var poleTarget = this.poleTargetPosition;
  70436. var mat1 = BoneIKController._tmpMats[0];
  70437. var mat2 = BoneIKController._tmpMats[1];
  70438. if (this.targetMesh) {
  70439. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70440. }
  70441. if (this.poleTargetBone) {
  70442. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70443. }
  70444. else if (this.poleTargetMesh) {
  70445. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70446. }
  70447. var bonePos = BoneIKController._tmpVecs[0];
  70448. var zaxis = BoneIKController._tmpVecs[1];
  70449. var xaxis = BoneIKController._tmpVecs[2];
  70450. var yaxis = BoneIKController._tmpVecs[3];
  70451. var upAxis = BoneIKController._tmpVecs[4];
  70452. var _tmpQuat = BoneIKController._tmpQuat;
  70453. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70454. poleTarget.subtractToRef(bonePos, upAxis);
  70455. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70456. upAxis.y = 1;
  70457. }
  70458. else {
  70459. upAxis.normalize();
  70460. }
  70461. target.subtractToRef(bonePos, yaxis);
  70462. yaxis.normalize();
  70463. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70464. zaxis.normalize();
  70465. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70466. xaxis.normalize();
  70467. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70468. var a = this._bone1Length;
  70469. var b = this._bone2Length;
  70470. var c = BABYLON.Vector3.Distance(bonePos, target);
  70471. if (this._maxReach > 0) {
  70472. c = Math.min(this._maxReach, c);
  70473. }
  70474. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70475. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70476. if (acosa > 1) {
  70477. acosa = 1;
  70478. }
  70479. if (acosb > 1) {
  70480. acosb = 1;
  70481. }
  70482. if (acosa < -1) {
  70483. acosa = -1;
  70484. }
  70485. if (acosb < -1) {
  70486. acosb = -1;
  70487. }
  70488. var angA = Math.acos(acosa);
  70489. var angB = Math.acos(acosb);
  70490. var angC = -angA - angB;
  70491. if (this._rightHandedSystem) {
  70492. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70493. mat2.multiplyToRef(mat1, mat1);
  70494. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70495. mat2.multiplyToRef(mat1, mat1);
  70496. }
  70497. else {
  70498. var _tmpVec = BoneIKController._tmpVecs[5];
  70499. _tmpVec.copyFrom(this._bendAxis);
  70500. _tmpVec.x *= -1;
  70501. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70502. mat2.multiplyToRef(mat1, mat1);
  70503. }
  70504. if (this.poleAngle) {
  70505. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70506. mat1.multiplyToRef(mat2, mat1);
  70507. }
  70508. if (this._bone1) {
  70509. if (this.slerpAmount < 1) {
  70510. if (!this._slerping) {
  70511. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70512. }
  70513. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70514. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70515. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70516. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70517. this._slerping = true;
  70518. }
  70519. else {
  70520. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70521. this._bone1Mat.copyFrom(mat1);
  70522. this._slerping = false;
  70523. }
  70524. }
  70525. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70526. this._bone2Ang = angC;
  70527. };
  70528. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70529. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70530. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70531. return BoneIKController;
  70532. }());
  70533. BABYLON.BoneIKController = BoneIKController;
  70534. })(BABYLON || (BABYLON = {}));
  70535. //# sourceMappingURL=babylon.boneIKController.js.map
  70536. var BABYLON;
  70537. (function (BABYLON) {
  70538. var BoneLookController = /** @class */ (function () {
  70539. /**
  70540. * Create a BoneLookController
  70541. * @param mesh the mesh that the bone belongs to
  70542. * @param bone the bone that will be looking to the target
  70543. * @param target the target Vector3 to look at
  70544. * @param settings optional settings:
  70545. * - maxYaw: the maximum angle the bone will yaw to
  70546. * - minYaw: the minimum angle the bone will yaw to
  70547. * - maxPitch: the maximum angle the bone will pitch to
  70548. * - minPitch: the minimum angle the bone will yaw to
  70549. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70550. * - upAxis: the up axis of the coordinate system
  70551. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70552. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70553. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70554. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70555. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70556. * - adjustRoll: used to make an adjustment to the roll of the bone
  70557. **/
  70558. function BoneLookController(mesh, bone, target, options) {
  70559. /**
  70560. * The up axis of the coordinate system that is used when the bone is rotated.
  70561. */
  70562. this.upAxis = BABYLON.Vector3.Up();
  70563. /**
  70564. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70565. */
  70566. this.upAxisSpace = BABYLON.Space.LOCAL;
  70567. /**
  70568. * Used to make an adjustment to the yaw of the bone.
  70569. */
  70570. this.adjustYaw = 0;
  70571. /**
  70572. * Used to make an adjustment to the pitch of the bone.
  70573. */
  70574. this.adjustPitch = 0;
  70575. /**
  70576. * Used to make an adjustment to the roll of the bone.
  70577. */
  70578. this.adjustRoll = 0;
  70579. /**
  70580. * 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).
  70581. */
  70582. this.slerpAmount = 1;
  70583. this._boneQuat = BABYLON.Quaternion.Identity();
  70584. this._slerping = false;
  70585. this._firstFrameSkipped = false;
  70586. this._fowardAxis = BABYLON.Vector3.Forward();
  70587. this.mesh = mesh;
  70588. this.bone = bone;
  70589. this.target = target;
  70590. if (options) {
  70591. if (options.adjustYaw) {
  70592. this.adjustYaw = options.adjustYaw;
  70593. }
  70594. if (options.adjustPitch) {
  70595. this.adjustPitch = options.adjustPitch;
  70596. }
  70597. if (options.adjustRoll) {
  70598. this.adjustRoll = options.adjustRoll;
  70599. }
  70600. if (options.maxYaw != null) {
  70601. this.maxYaw = options.maxYaw;
  70602. }
  70603. else {
  70604. this.maxYaw = Math.PI;
  70605. }
  70606. if (options.minYaw != null) {
  70607. this.minYaw = options.minYaw;
  70608. }
  70609. else {
  70610. this.minYaw = -Math.PI;
  70611. }
  70612. if (options.maxPitch != null) {
  70613. this.maxPitch = options.maxPitch;
  70614. }
  70615. else {
  70616. this.maxPitch = Math.PI;
  70617. }
  70618. if (options.minPitch != null) {
  70619. this.minPitch = options.minPitch;
  70620. }
  70621. else {
  70622. this.minPitch = -Math.PI;
  70623. }
  70624. if (options.slerpAmount != null) {
  70625. this.slerpAmount = options.slerpAmount;
  70626. }
  70627. if (options.upAxis != null) {
  70628. this.upAxis = options.upAxis;
  70629. }
  70630. if (options.upAxisSpace != null) {
  70631. this.upAxisSpace = options.upAxisSpace;
  70632. }
  70633. if (options.yawAxis != null || options.pitchAxis != null) {
  70634. var newYawAxis = BABYLON.Axis.Y;
  70635. var newPitchAxis = BABYLON.Axis.X;
  70636. if (options.yawAxis != null) {
  70637. newYawAxis = options.yawAxis.clone();
  70638. newYawAxis.normalize();
  70639. }
  70640. if (options.pitchAxis != null) {
  70641. newPitchAxis = options.pitchAxis.clone();
  70642. newPitchAxis.normalize();
  70643. }
  70644. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70645. this._transformYawPitch = BABYLON.Matrix.Identity();
  70646. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70647. this._transformYawPitchInv = this._transformYawPitch.clone();
  70648. this._transformYawPitch.invert();
  70649. }
  70650. }
  70651. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70652. this.upAxisSpace = BABYLON.Space.LOCAL;
  70653. }
  70654. }
  70655. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70656. /**
  70657. * Get/set the minimum yaw angle that the bone can look to.
  70658. */
  70659. get: function () {
  70660. return this._minYaw;
  70661. },
  70662. set: function (value) {
  70663. this._minYaw = value;
  70664. this._minYawSin = Math.sin(value);
  70665. this._minYawCos = Math.cos(value);
  70666. if (this._maxYaw != null) {
  70667. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70668. this._yawRange = this._maxYaw - this._minYaw;
  70669. }
  70670. },
  70671. enumerable: true,
  70672. configurable: true
  70673. });
  70674. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70675. /**
  70676. * Get/set the maximum yaw angle that the bone can look to.
  70677. */
  70678. get: function () {
  70679. return this._maxYaw;
  70680. },
  70681. set: function (value) {
  70682. this._maxYaw = value;
  70683. this._maxYawSin = Math.sin(value);
  70684. this._maxYawCos = Math.cos(value);
  70685. if (this._minYaw != null) {
  70686. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70687. this._yawRange = this._maxYaw - this._minYaw;
  70688. }
  70689. },
  70690. enumerable: true,
  70691. configurable: true
  70692. });
  70693. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  70694. /**
  70695. * Get/set the minimum pitch angle that the bone can look to.
  70696. */
  70697. get: function () {
  70698. return this._minPitch;
  70699. },
  70700. set: function (value) {
  70701. this._minPitch = value;
  70702. this._minPitchTan = Math.tan(value);
  70703. },
  70704. enumerable: true,
  70705. configurable: true
  70706. });
  70707. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  70708. /**
  70709. * Get/set the maximum pitch angle that the bone can look to.
  70710. */
  70711. get: function () {
  70712. return this._maxPitch;
  70713. },
  70714. set: function (value) {
  70715. this._maxPitch = value;
  70716. this._maxPitchTan = Math.tan(value);
  70717. },
  70718. enumerable: true,
  70719. configurable: true
  70720. });
  70721. /**
  70722. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  70723. */
  70724. BoneLookController.prototype.update = function () {
  70725. //skip the first frame when slerping so that the mesh rotation is correct
  70726. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  70727. this._firstFrameSkipped = true;
  70728. return;
  70729. }
  70730. var bone = this.bone;
  70731. var bonePos = BoneLookController._tmpVecs[0];
  70732. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  70733. var target = this.target;
  70734. var _tmpMat1 = BoneLookController._tmpMats[0];
  70735. var _tmpMat2 = BoneLookController._tmpMats[1];
  70736. var mesh = this.mesh;
  70737. var parentBone = bone.getParent();
  70738. var upAxis = BoneLookController._tmpVecs[1];
  70739. upAxis.copyFrom(this.upAxis);
  70740. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  70741. if (this._transformYawPitch) {
  70742. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  70743. }
  70744. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  70745. }
  70746. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  70747. mesh.getDirectionToRef(upAxis, upAxis);
  70748. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  70749. upAxis.normalize();
  70750. }
  70751. }
  70752. var checkYaw = false;
  70753. var checkPitch = false;
  70754. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  70755. checkYaw = true;
  70756. }
  70757. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  70758. checkPitch = true;
  70759. }
  70760. if (checkYaw || checkPitch) {
  70761. var spaceMat = BoneLookController._tmpMats[2];
  70762. var spaceMatInv = BoneLookController._tmpMats[3];
  70763. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  70764. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  70765. }
  70766. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  70767. spaceMat.copyFrom(mesh.getWorldMatrix());
  70768. }
  70769. else {
  70770. var forwardAxis = BoneLookController._tmpVecs[2];
  70771. forwardAxis.copyFrom(this._fowardAxis);
  70772. if (this._transformYawPitch) {
  70773. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  70774. }
  70775. if (parentBone) {
  70776. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  70777. }
  70778. else {
  70779. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  70780. }
  70781. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  70782. rightAxis.normalize();
  70783. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  70784. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  70785. }
  70786. spaceMat.invertToRef(spaceMatInv);
  70787. var xzlen = null;
  70788. if (checkPitch) {
  70789. var localTarget = BoneLookController._tmpVecs[3];
  70790. target.subtractToRef(bonePos, localTarget);
  70791. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70792. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70793. var pitch = Math.atan2(localTarget.y, xzlen);
  70794. var newPitch = pitch;
  70795. if (pitch > this._maxPitch) {
  70796. localTarget.y = this._maxPitchTan * xzlen;
  70797. newPitch = this._maxPitch;
  70798. }
  70799. else if (pitch < this._minPitch) {
  70800. localTarget.y = this._minPitchTan * xzlen;
  70801. newPitch = this._minPitch;
  70802. }
  70803. if (pitch != newPitch) {
  70804. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70805. localTarget.addInPlace(bonePos);
  70806. target = localTarget;
  70807. }
  70808. }
  70809. if (checkYaw) {
  70810. var localTarget = BoneLookController._tmpVecs[4];
  70811. target.subtractToRef(bonePos, localTarget);
  70812. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70813. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70814. var newYaw = yaw;
  70815. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70816. if (xzlen == null) {
  70817. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70818. }
  70819. if (this._yawRange > Math.PI) {
  70820. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70821. localTarget.z = this._maxYawCos * xzlen;
  70822. localTarget.x = this._maxYawSin * xzlen;
  70823. newYaw = this._maxYaw;
  70824. }
  70825. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70826. localTarget.z = this._minYawCos * xzlen;
  70827. localTarget.x = this._minYawSin * xzlen;
  70828. newYaw = this._minYaw;
  70829. }
  70830. }
  70831. else {
  70832. if (yaw > this._maxYaw) {
  70833. localTarget.z = this._maxYawCos * xzlen;
  70834. localTarget.x = this._maxYawSin * xzlen;
  70835. newYaw = this._maxYaw;
  70836. }
  70837. else if (yaw < this._minYaw) {
  70838. localTarget.z = this._minYawCos * xzlen;
  70839. localTarget.x = this._minYawSin * xzlen;
  70840. newYaw = this._minYaw;
  70841. }
  70842. }
  70843. }
  70844. if (this._slerping && this._yawRange > Math.PI) {
  70845. //are we going to be crossing into the min/max region?
  70846. var boneFwd = BoneLookController._tmpVecs[8];
  70847. boneFwd.copyFrom(BABYLON.Axis.Z);
  70848. if (this._transformYawPitch) {
  70849. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70850. }
  70851. var boneRotMat = BoneLookController._tmpMats[4];
  70852. this._boneQuat.toRotationMatrix(boneRotMat);
  70853. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70854. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70855. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70856. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70857. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70858. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70859. if (angBtwTar > angBtwMidYaw) {
  70860. if (xzlen == null) {
  70861. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70862. }
  70863. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70864. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70865. if (angBtwMin < angBtwMax) {
  70866. newYaw = boneYaw + Math.PI * .75;
  70867. localTarget.z = Math.cos(newYaw) * xzlen;
  70868. localTarget.x = Math.sin(newYaw) * xzlen;
  70869. }
  70870. else {
  70871. newYaw = boneYaw - Math.PI * .75;
  70872. localTarget.z = Math.cos(newYaw) * xzlen;
  70873. localTarget.x = Math.sin(newYaw) * xzlen;
  70874. }
  70875. }
  70876. }
  70877. if (yaw != newYaw) {
  70878. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70879. localTarget.addInPlace(bonePos);
  70880. target = localTarget;
  70881. }
  70882. }
  70883. }
  70884. var zaxis = BoneLookController._tmpVecs[5];
  70885. var xaxis = BoneLookController._tmpVecs[6];
  70886. var yaxis = BoneLookController._tmpVecs[7];
  70887. var _tmpQuat = BoneLookController._tmpQuat;
  70888. target.subtractToRef(bonePos, zaxis);
  70889. zaxis.normalize();
  70890. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70891. xaxis.normalize();
  70892. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70893. yaxis.normalize();
  70894. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70895. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70896. return;
  70897. }
  70898. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70899. return;
  70900. }
  70901. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70902. return;
  70903. }
  70904. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70905. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70906. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70907. }
  70908. if (this.slerpAmount < 1) {
  70909. if (!this._slerping) {
  70910. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70911. }
  70912. if (this._transformYawPitch) {
  70913. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70914. }
  70915. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70916. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70917. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70918. this._slerping = true;
  70919. }
  70920. else {
  70921. if (this._transformYawPitch) {
  70922. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70923. }
  70924. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70925. this._slerping = false;
  70926. }
  70927. };
  70928. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70929. var angDiff = ang2 - ang1;
  70930. angDiff %= Math.PI * 2;
  70931. if (angDiff > Math.PI) {
  70932. angDiff -= Math.PI * 2;
  70933. }
  70934. else if (angDiff < -Math.PI) {
  70935. angDiff += Math.PI * 2;
  70936. }
  70937. return angDiff;
  70938. };
  70939. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70940. ang1 %= (2 * Math.PI);
  70941. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70942. ang2 %= (2 * Math.PI);
  70943. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70944. var ab = 0;
  70945. if (ang1 < ang2) {
  70946. ab = ang2 - ang1;
  70947. }
  70948. else {
  70949. ab = ang1 - ang2;
  70950. }
  70951. if (ab > Math.PI) {
  70952. ab = Math.PI * 2 - ab;
  70953. }
  70954. return ab;
  70955. };
  70956. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70957. ang %= (2 * Math.PI);
  70958. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70959. ang1 %= (2 * Math.PI);
  70960. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70961. ang2 %= (2 * Math.PI);
  70962. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70963. if (ang1 < ang2) {
  70964. if (ang > ang1 && ang < ang2) {
  70965. return true;
  70966. }
  70967. }
  70968. else {
  70969. if (ang > ang2 && ang < ang1) {
  70970. return true;
  70971. }
  70972. }
  70973. return false;
  70974. };
  70975. 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()];
  70976. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70977. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70978. return BoneLookController;
  70979. }());
  70980. BABYLON.BoneLookController = BoneLookController;
  70981. })(BABYLON || (BABYLON = {}));
  70982. //# sourceMappingURL=babylon.boneLookController.js.map
  70983. var BABYLON;
  70984. (function (BABYLON) {
  70985. var Skeleton = /** @class */ (function () {
  70986. function Skeleton(name, id, scene) {
  70987. this.name = name;
  70988. this.id = id;
  70989. this.bones = new Array();
  70990. this.needInitialSkinMatrix = false;
  70991. this._isDirty = true;
  70992. this._meshesWithPoseMatrix = new Array();
  70993. this._identity = BABYLON.Matrix.Identity();
  70994. this._ranges = {};
  70995. this._lastAbsoluteTransformsUpdateId = -1;
  70996. /**
  70997. * Specifies if the skeleton should be serialized.
  70998. */
  70999. this.doNotSerialize = false;
  71000. // Events
  71001. /**
  71002. * An event triggered before computing the skeleton's matrices
  71003. * @type {BABYLON.Observable}
  71004. */
  71005. this.onBeforeComputeObservable = new BABYLON.Observable();
  71006. this.bones = [];
  71007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71008. scene.skeletons.push(this);
  71009. //make sure it will recalculate the matrix next time prepare is called.
  71010. this._isDirty = true;
  71011. }
  71012. // Members
  71013. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71014. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71015. return mesh._bonesTransformMatrices;
  71016. }
  71017. if (!this._transformMatrices) {
  71018. this.prepare();
  71019. }
  71020. return this._transformMatrices;
  71021. };
  71022. Skeleton.prototype.getScene = function () {
  71023. return this._scene;
  71024. };
  71025. // Methods
  71026. /**
  71027. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71028. */
  71029. Skeleton.prototype.toString = function (fullDetails) {
  71030. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71031. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71032. if (fullDetails) {
  71033. ret += ", Ranges: {";
  71034. var first = true;
  71035. for (var name_1 in this._ranges) {
  71036. if (first) {
  71037. ret += ", ";
  71038. first = false;
  71039. }
  71040. ret += name_1;
  71041. }
  71042. ret += "}";
  71043. }
  71044. return ret;
  71045. };
  71046. /**
  71047. * Get bone's index searching by name
  71048. * @param {string} name is bone's name to search for
  71049. * @return {number} Indice of the bone. Returns -1 if not found
  71050. */
  71051. Skeleton.prototype.getBoneIndexByName = function (name) {
  71052. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71053. if (this.bones[boneIndex].name === name) {
  71054. return boneIndex;
  71055. }
  71056. }
  71057. return -1;
  71058. };
  71059. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71060. // check name not already in use
  71061. if (!this._ranges[name]) {
  71062. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71063. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71064. if (this.bones[i].animations[0]) {
  71065. this.bones[i].animations[0].createRange(name, from, to);
  71066. }
  71067. }
  71068. }
  71069. };
  71070. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71071. if (deleteFrames === void 0) { deleteFrames = true; }
  71072. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71073. if (this.bones[i].animations[0]) {
  71074. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71075. }
  71076. }
  71077. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71078. };
  71079. Skeleton.prototype.getAnimationRange = function (name) {
  71080. return this._ranges[name];
  71081. };
  71082. /**
  71083. * Returns as an Array, all AnimationRanges defined on this skeleton
  71084. */
  71085. Skeleton.prototype.getAnimationRanges = function () {
  71086. var animationRanges = [];
  71087. var name;
  71088. var i = 0;
  71089. for (name in this._ranges) {
  71090. animationRanges[i] = this._ranges[name];
  71091. i++;
  71092. }
  71093. return animationRanges;
  71094. };
  71095. /**
  71096. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71097. */
  71098. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71099. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71100. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71101. return false;
  71102. }
  71103. var ret = true;
  71104. var frameOffset = this._getHighestAnimationFrame() + 1;
  71105. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71106. var boneDict = {};
  71107. var sourceBones = source.bones;
  71108. var nBones;
  71109. var i;
  71110. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71111. boneDict[sourceBones[i].name] = sourceBones[i];
  71112. }
  71113. if (this.bones.length !== sourceBones.length) {
  71114. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71115. ret = false;
  71116. }
  71117. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71118. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71119. var boneName = this.bones[i].name;
  71120. var sourceBone = boneDict[boneName];
  71121. if (sourceBone) {
  71122. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71123. }
  71124. else {
  71125. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71126. ret = false;
  71127. }
  71128. }
  71129. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71130. var range = source.getAnimationRange(name);
  71131. if (range) {
  71132. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71133. }
  71134. return ret;
  71135. };
  71136. Skeleton.prototype.returnToRest = function () {
  71137. for (var index = 0; index < this.bones.length; index++) {
  71138. this.bones[index].returnToRest();
  71139. }
  71140. };
  71141. Skeleton.prototype._getHighestAnimationFrame = function () {
  71142. var ret = 0;
  71143. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71144. if (this.bones[i].animations[0]) {
  71145. var highest = this.bones[i].animations[0].getHighestFrame();
  71146. if (ret < highest) {
  71147. ret = highest;
  71148. }
  71149. }
  71150. }
  71151. return ret;
  71152. };
  71153. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71154. var range = this.getAnimationRange(name);
  71155. if (!range) {
  71156. return null;
  71157. }
  71158. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71159. };
  71160. Skeleton.prototype._markAsDirty = function () {
  71161. this._isDirty = true;
  71162. };
  71163. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71164. this._meshesWithPoseMatrix.push(mesh);
  71165. };
  71166. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71167. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71168. if (index > -1) {
  71169. this._meshesWithPoseMatrix.splice(index, 1);
  71170. }
  71171. };
  71172. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71173. this.onBeforeComputeObservable.notifyObservers(this);
  71174. for (var index = 0; index < this.bones.length; index++) {
  71175. var bone = this.bones[index];
  71176. var parentBone = bone.getParent();
  71177. if (parentBone) {
  71178. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71179. }
  71180. else {
  71181. if (initialSkinMatrix) {
  71182. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71183. }
  71184. else {
  71185. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71186. }
  71187. }
  71188. if (bone._index !== -1) {
  71189. var mappedIndex = bone._index === null ? index : bone._index;
  71190. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71191. }
  71192. }
  71193. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71194. };
  71195. Skeleton.prototype.prepare = function () {
  71196. if (!this._isDirty) {
  71197. return;
  71198. }
  71199. if (this.needInitialSkinMatrix) {
  71200. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71201. var mesh = this._meshesWithPoseMatrix[index];
  71202. var poseMatrix = mesh.getPoseMatrix();
  71203. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71204. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71205. }
  71206. if (this._synchronizedWithMesh !== mesh) {
  71207. this._synchronizedWithMesh = mesh;
  71208. // Prepare bones
  71209. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71210. var bone = this.bones[boneIndex];
  71211. if (!bone.getParent()) {
  71212. var matrix = bone.getBaseMatrix();
  71213. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71214. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71215. }
  71216. }
  71217. }
  71218. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71219. }
  71220. }
  71221. else {
  71222. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71223. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71224. }
  71225. this._computeTransformMatrices(this._transformMatrices, null);
  71226. }
  71227. this._isDirty = false;
  71228. this._scene._activeBones.addCount(this.bones.length, false);
  71229. };
  71230. Skeleton.prototype.getAnimatables = function () {
  71231. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71232. this._animatables = [];
  71233. for (var index = 0; index < this.bones.length; index++) {
  71234. this._animatables.push(this.bones[index]);
  71235. }
  71236. }
  71237. return this._animatables;
  71238. };
  71239. Skeleton.prototype.clone = function (name, id) {
  71240. var result = new Skeleton(name, id || name, this._scene);
  71241. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71242. for (var index = 0; index < this.bones.length; index++) {
  71243. var source = this.bones[index];
  71244. var parentBone = null;
  71245. var parent_1 = source.getParent();
  71246. if (parent_1) {
  71247. var parentIndex = this.bones.indexOf(parent_1);
  71248. parentBone = result.bones[parentIndex];
  71249. }
  71250. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71251. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71252. }
  71253. if (this._ranges) {
  71254. result._ranges = {};
  71255. for (var rangeName in this._ranges) {
  71256. var range = this._ranges[rangeName];
  71257. if (range) {
  71258. result._ranges[rangeName] = range.clone();
  71259. }
  71260. }
  71261. }
  71262. this._isDirty = true;
  71263. return result;
  71264. };
  71265. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71266. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71267. this.bones.forEach(function (bone) {
  71268. bone.animations.forEach(function (animation) {
  71269. animation.enableBlending = true;
  71270. animation.blendingSpeed = blendingSpeed;
  71271. });
  71272. });
  71273. };
  71274. Skeleton.prototype.dispose = function () {
  71275. this._meshesWithPoseMatrix = [];
  71276. // Animations
  71277. this.getScene().stopAnimation(this);
  71278. // Remove from scene
  71279. this.getScene().removeSkeleton(this);
  71280. };
  71281. Skeleton.prototype.serialize = function () {
  71282. var serializationObject = {};
  71283. serializationObject.name = this.name;
  71284. serializationObject.id = this.id;
  71285. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71286. serializationObject.bones = [];
  71287. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71288. for (var index = 0; index < this.bones.length; index++) {
  71289. var bone = this.bones[index];
  71290. var parent_2 = bone.getParent();
  71291. var serializedBone = {
  71292. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71293. name: bone.name,
  71294. matrix: bone.getBaseMatrix().toArray(),
  71295. rest: bone.getRestPose().toArray()
  71296. };
  71297. serializationObject.bones.push(serializedBone);
  71298. if (bone.length) {
  71299. serializedBone.length = bone.length;
  71300. }
  71301. if (bone.animations && bone.animations.length > 0) {
  71302. serializedBone.animation = bone.animations[0].serialize();
  71303. }
  71304. serializationObject.ranges = [];
  71305. for (var name in this._ranges) {
  71306. var source = this._ranges[name];
  71307. if (!source) {
  71308. continue;
  71309. }
  71310. var range = {};
  71311. range.name = name;
  71312. range.from = source.from;
  71313. range.to = source.to;
  71314. serializationObject.ranges.push(range);
  71315. }
  71316. }
  71317. return serializationObject;
  71318. };
  71319. Skeleton.Parse = function (parsedSkeleton, scene) {
  71320. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71321. if (parsedSkeleton.dimensionsAtRest) {
  71322. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71323. }
  71324. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71325. var index;
  71326. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71327. var parsedBone = parsedSkeleton.bones[index];
  71328. var parentBone = null;
  71329. if (parsedBone.parentBoneIndex > -1) {
  71330. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71331. }
  71332. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71333. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71334. if (parsedBone.length) {
  71335. bone.length = parsedBone.length;
  71336. }
  71337. if (parsedBone.animation) {
  71338. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71339. }
  71340. }
  71341. // placed after bones, so createAnimationRange can cascade down
  71342. if (parsedSkeleton.ranges) {
  71343. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71344. var data = parsedSkeleton.ranges[index];
  71345. skeleton.createAnimationRange(data.name, data.from, data.to);
  71346. }
  71347. }
  71348. return skeleton;
  71349. };
  71350. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71351. if (forceUpdate === void 0) { forceUpdate = false; }
  71352. var renderId = this._scene.getRenderId();
  71353. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71354. this.bones[0].computeAbsoluteTransforms();
  71355. this._lastAbsoluteTransformsUpdateId = renderId;
  71356. }
  71357. };
  71358. Skeleton.prototype.getPoseMatrix = function () {
  71359. var poseMatrix = null;
  71360. if (this._meshesWithPoseMatrix.length > 0) {
  71361. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71362. }
  71363. return poseMatrix;
  71364. };
  71365. Skeleton.prototype.sortBones = function () {
  71366. var bones = new Array();
  71367. var visited = new Array(this.bones.length);
  71368. for (var index = 0; index < this.bones.length; index++) {
  71369. this._sortBones(index, bones, visited);
  71370. }
  71371. this.bones = bones;
  71372. };
  71373. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71374. if (visited[index]) {
  71375. return;
  71376. }
  71377. visited[index] = true;
  71378. var bone = this.bones[index];
  71379. if (bone._index === undefined) {
  71380. bone._index = index;
  71381. }
  71382. var parentBone = bone.getParent();
  71383. if (parentBone) {
  71384. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71385. }
  71386. bones.push(bone);
  71387. };
  71388. return Skeleton;
  71389. }());
  71390. BABYLON.Skeleton = Skeleton;
  71391. })(BABYLON || (BABYLON = {}));
  71392. //# sourceMappingURL=babylon.skeleton.js.map
  71393. var BABYLON;
  71394. (function (BABYLON) {
  71395. var SphericalPolynomial = /** @class */ (function () {
  71396. function SphericalPolynomial() {
  71397. this.x = BABYLON.Vector3.Zero();
  71398. this.y = BABYLON.Vector3.Zero();
  71399. this.z = BABYLON.Vector3.Zero();
  71400. this.xx = BABYLON.Vector3.Zero();
  71401. this.yy = BABYLON.Vector3.Zero();
  71402. this.zz = BABYLON.Vector3.Zero();
  71403. this.xy = BABYLON.Vector3.Zero();
  71404. this.yz = BABYLON.Vector3.Zero();
  71405. this.zx = BABYLON.Vector3.Zero();
  71406. }
  71407. SphericalPolynomial.prototype.addAmbient = function (color) {
  71408. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71409. this.xx = this.xx.add(colorVector);
  71410. this.yy = this.yy.add(colorVector);
  71411. this.zz = this.zz.add(colorVector);
  71412. };
  71413. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71414. var result = new SphericalPolynomial();
  71415. result.x = harmonics.L11.scale(1.02333);
  71416. result.y = harmonics.L1_1.scale(1.02333);
  71417. result.z = harmonics.L10.scale(1.02333);
  71418. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71419. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71420. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71421. result.yz = harmonics.L2_1.scale(0.858086);
  71422. result.zx = harmonics.L21.scale(0.858086);
  71423. result.xy = harmonics.L2_2.scale(0.858086);
  71424. result.scale(1.0 / Math.PI);
  71425. return result;
  71426. };
  71427. SphericalPolynomial.prototype.scale = function (scale) {
  71428. this.x = this.x.scale(scale);
  71429. this.y = this.y.scale(scale);
  71430. this.z = this.z.scale(scale);
  71431. this.xx = this.xx.scale(scale);
  71432. this.yy = this.yy.scale(scale);
  71433. this.zz = this.zz.scale(scale);
  71434. this.yz = this.yz.scale(scale);
  71435. this.zx = this.zx.scale(scale);
  71436. this.xy = this.xy.scale(scale);
  71437. };
  71438. return SphericalPolynomial;
  71439. }());
  71440. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71441. var SphericalHarmonics = /** @class */ (function () {
  71442. function SphericalHarmonics() {
  71443. this.L00 = BABYLON.Vector3.Zero();
  71444. this.L1_1 = BABYLON.Vector3.Zero();
  71445. this.L10 = BABYLON.Vector3.Zero();
  71446. this.L11 = BABYLON.Vector3.Zero();
  71447. this.L2_2 = BABYLON.Vector3.Zero();
  71448. this.L2_1 = BABYLON.Vector3.Zero();
  71449. this.L20 = BABYLON.Vector3.Zero();
  71450. this.L21 = BABYLON.Vector3.Zero();
  71451. this.L22 = BABYLON.Vector3.Zero();
  71452. }
  71453. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71454. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71455. var c = colorVector.scale(deltaSolidAngle);
  71456. this.L00 = this.L00.add(c.scale(0.282095));
  71457. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71458. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71459. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71460. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71461. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71462. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71463. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71464. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71465. };
  71466. SphericalHarmonics.prototype.scale = function (scale) {
  71467. this.L00 = this.L00.scale(scale);
  71468. this.L1_1 = this.L1_1.scale(scale);
  71469. this.L10 = this.L10.scale(scale);
  71470. this.L11 = this.L11.scale(scale);
  71471. this.L2_2 = this.L2_2.scale(scale);
  71472. this.L2_1 = this.L2_1.scale(scale);
  71473. this.L20 = this.L20.scale(scale);
  71474. this.L21 = this.L21.scale(scale);
  71475. this.L22 = this.L22.scale(scale);
  71476. };
  71477. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71478. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71479. //
  71480. // E_lm = A_l * L_lm
  71481. //
  71482. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71483. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71484. // the scaling factors are given in equation 9.
  71485. // Constant (Band 0)
  71486. this.L00 = this.L00.scale(3.141593);
  71487. // Linear (Band 1)
  71488. this.L1_1 = this.L1_1.scale(2.094395);
  71489. this.L10 = this.L10.scale(2.094395);
  71490. this.L11 = this.L11.scale(2.094395);
  71491. // Quadratic (Band 2)
  71492. this.L2_2 = this.L2_2.scale(0.785398);
  71493. this.L2_1 = this.L2_1.scale(0.785398);
  71494. this.L20 = this.L20.scale(0.785398);
  71495. this.L21 = this.L21.scale(0.785398);
  71496. this.L22 = this.L22.scale(0.785398);
  71497. };
  71498. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71499. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71500. // L = (1/pi) * E * rho
  71501. //
  71502. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71503. this.scale(1.0 / Math.PI);
  71504. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71505. // (The pixel shader must apply albedo after texture fetches, etc).
  71506. };
  71507. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71508. var result = new SphericalHarmonics();
  71509. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71510. result.L1_1 = polynomial.y.scale(0.977204);
  71511. result.L10 = polynomial.z.scale(0.977204);
  71512. result.L11 = polynomial.x.scale(0.977204);
  71513. result.L2_2 = polynomial.xy.scale(1.16538);
  71514. result.L2_1 = polynomial.yz.scale(1.16538);
  71515. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71516. result.L21 = polynomial.zx.scale(1.16538);
  71517. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71518. result.scale(Math.PI);
  71519. return result;
  71520. };
  71521. return SphericalHarmonics;
  71522. }());
  71523. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71524. })(BABYLON || (BABYLON = {}));
  71525. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71526. var BABYLON;
  71527. (function (BABYLON) {
  71528. var FileFaceOrientation = /** @class */ (function () {
  71529. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71530. this.name = name;
  71531. this.worldAxisForNormal = worldAxisForNormal;
  71532. this.worldAxisForFileX = worldAxisForFileX;
  71533. this.worldAxisForFileY = worldAxisForFileY;
  71534. }
  71535. return FileFaceOrientation;
  71536. }());
  71537. ;
  71538. /**
  71539. * Helper class dealing with the extraction of spherical polynomial dataArray
  71540. * from a cube map.
  71541. */
  71542. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71543. function CubeMapToSphericalPolynomialTools() {
  71544. }
  71545. /**
  71546. * Converts a texture to the according Spherical Polynomial data.
  71547. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71548. *
  71549. * @param texture The texture to extract the information from.
  71550. * @return The Spherical Polynomial data.
  71551. */
  71552. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71553. if (!texture.isCube) {
  71554. // Only supports cube Textures currently.
  71555. return null;
  71556. }
  71557. var size = texture.getSize().width;
  71558. var right = texture.readPixels(0);
  71559. var left = texture.readPixels(1);
  71560. var up;
  71561. var down;
  71562. if (texture.isRenderTarget) {
  71563. up = texture.readPixels(3);
  71564. down = texture.readPixels(2);
  71565. }
  71566. else {
  71567. up = texture.readPixels(2);
  71568. down = texture.readPixels(3);
  71569. }
  71570. var front = texture.readPixels(4);
  71571. var back = texture.readPixels(5);
  71572. var gammaSpace = texture.gammaSpace;
  71573. // Always read as RGBA.
  71574. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71575. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71576. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71577. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71578. }
  71579. var cubeInfo = {
  71580. size: size,
  71581. right: right,
  71582. left: left,
  71583. up: up,
  71584. down: down,
  71585. front: front,
  71586. back: back,
  71587. format: format,
  71588. type: type,
  71589. gammaSpace: gammaSpace,
  71590. };
  71591. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71592. };
  71593. /**
  71594. * Converts a cubemap to the according Spherical Polynomial data.
  71595. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71596. *
  71597. * @param cubeInfo The Cube map to extract the information from.
  71598. * @return The Spherical Polynomial data.
  71599. */
  71600. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71601. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71602. var totalSolidAngle = 0.0;
  71603. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71604. var du = 2.0 / cubeInfo.size;
  71605. var dv = du;
  71606. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71607. var minUV = du * 0.5 - 1.0;
  71608. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71609. var fileFace = this.FileFaces[faceIndex];
  71610. var dataArray = cubeInfo[fileFace.name];
  71611. var v = minUV;
  71612. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71613. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71614. // Because SP is still linear, so summation is fine in that basis.
  71615. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71616. for (var y = 0; y < cubeInfo.size; y++) {
  71617. var u = minUV;
  71618. for (var x = 0; x < cubeInfo.size; x++) {
  71619. // World direction (not normalised)
  71620. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71621. worldDirection.normalize();
  71622. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71623. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71624. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71625. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71626. // Handle Integer types.
  71627. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71628. r /= 255;
  71629. g /= 255;
  71630. b /= 255;
  71631. }
  71632. // Handle Gamma space textures.
  71633. if (cubeInfo.gammaSpace) {
  71634. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71635. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71636. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71637. }
  71638. var color = new BABYLON.Color3(r, g, b);
  71639. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71640. totalSolidAngle += deltaSolidAngle;
  71641. u += du;
  71642. }
  71643. v += dv;
  71644. }
  71645. }
  71646. // Solid angle for entire sphere is 4*pi
  71647. var sphereSolidAngle = 4.0 * Math.PI;
  71648. // Adjust the solid angle to allow for how many faces we processed.
  71649. var facesProcessed = 6.0;
  71650. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71651. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71652. // This is needed because the numerical integration over the cube uses a
  71653. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71654. // and also to compensate for accumulative error due to float precision in the summation.
  71655. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71656. sphericalHarmonics.scale(correctionFactor);
  71657. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71658. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71659. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71660. };
  71661. CubeMapToSphericalPolynomialTools.FileFaces = [
  71662. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71663. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71664. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71665. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71666. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71667. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71668. ];
  71669. return CubeMapToSphericalPolynomialTools;
  71670. }());
  71671. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71672. })(BABYLON || (BABYLON = {}));
  71673. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71674. var BABYLON;
  71675. (function (BABYLON) {
  71676. /**
  71677. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71678. */
  71679. var PanoramaToCubeMapTools = /** @class */ (function () {
  71680. function PanoramaToCubeMapTools() {
  71681. }
  71682. /**
  71683. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71684. *
  71685. * @param float32Array The source data.
  71686. * @param inputWidth The width of the input panorama.
  71687. * @param inputhHeight The height of the input panorama.
  71688. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  71689. * @return The cubemap data
  71690. */
  71691. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  71692. if (!float32Array) {
  71693. throw "ConvertPanoramaToCubemap: input cannot be null";
  71694. }
  71695. if (float32Array.length != inputWidth * inputHeight * 3) {
  71696. throw "ConvertPanoramaToCubemap: input size is wrong";
  71697. }
  71698. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  71699. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  71700. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  71701. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  71702. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  71703. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  71704. return {
  71705. front: textureFront,
  71706. back: textureBack,
  71707. left: textureLeft,
  71708. right: textureRight,
  71709. up: textureUp,
  71710. down: textureDown,
  71711. size: size,
  71712. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  71713. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  71714. gammaSpace: false,
  71715. };
  71716. };
  71717. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  71718. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  71719. var textureArray = new Float32Array(buffer);
  71720. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  71721. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  71722. var dy = 1 / texSize;
  71723. var fy = 0;
  71724. for (var y = 0; y < texSize; y++) {
  71725. var xv1 = faceData[0];
  71726. var xv2 = faceData[2];
  71727. for (var x = 0; x < texSize; x++) {
  71728. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  71729. v.normalize();
  71730. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  71731. // 3 channels per pixels
  71732. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  71733. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  71734. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  71735. xv1 = xv1.add(rotDX1);
  71736. xv2 = xv2.add(rotDX2);
  71737. }
  71738. fy += dy;
  71739. }
  71740. return textureArray;
  71741. };
  71742. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  71743. var theta = Math.atan2(vDir.z, vDir.x);
  71744. var phi = Math.acos(vDir.y);
  71745. while (theta < -Math.PI)
  71746. theta += 2 * Math.PI;
  71747. while (theta > Math.PI)
  71748. theta -= 2 * Math.PI;
  71749. var dx = theta / Math.PI;
  71750. var dy = phi / Math.PI;
  71751. // recenter.
  71752. dx = dx * 0.5 + 0.5;
  71753. var px = Math.round(dx * inputWidth);
  71754. if (px < 0)
  71755. px = 0;
  71756. else if (px >= inputWidth)
  71757. px = inputWidth - 1;
  71758. var py = Math.round(dy * inputHeight);
  71759. if (py < 0)
  71760. py = 0;
  71761. else if (py >= inputHeight)
  71762. py = inputHeight - 1;
  71763. var inputY = (inputHeight - py - 1);
  71764. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  71765. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  71766. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  71767. return {
  71768. r: r,
  71769. g: g,
  71770. b: b
  71771. };
  71772. };
  71773. PanoramaToCubeMapTools.FACE_FRONT = [
  71774. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71775. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71776. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71777. new BABYLON.Vector3(1.0, 1.0, -1.0)
  71778. ];
  71779. PanoramaToCubeMapTools.FACE_BACK = [
  71780. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71781. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71782. new BABYLON.Vector3(1.0, 1.0, 1.0),
  71783. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  71784. ];
  71785. PanoramaToCubeMapTools.FACE_RIGHT = [
  71786. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71787. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71788. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71789. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71790. ];
  71791. PanoramaToCubeMapTools.FACE_LEFT = [
  71792. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71793. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71794. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71795. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  71796. ];
  71797. PanoramaToCubeMapTools.FACE_DOWN = [
  71798. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71799. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71800. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71801. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71802. ];
  71803. PanoramaToCubeMapTools.FACE_UP = [
  71804. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71805. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71806. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71807. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71808. ];
  71809. return PanoramaToCubeMapTools;
  71810. }());
  71811. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71812. })(BABYLON || (BABYLON = {}));
  71813. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71814. var BABYLON;
  71815. (function (BABYLON) {
  71816. ;
  71817. /**
  71818. * This groups tools to convert HDR texture to native colors array.
  71819. */
  71820. var HDRTools = /** @class */ (function () {
  71821. function HDRTools() {
  71822. }
  71823. HDRTools.Ldexp = function (mantissa, exponent) {
  71824. if (exponent > 1023) {
  71825. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71826. }
  71827. if (exponent < -1074) {
  71828. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71829. }
  71830. return mantissa * Math.pow(2, exponent);
  71831. };
  71832. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71833. if (exponent > 0) {
  71834. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71835. float32array[index + 0] = red * exponent;
  71836. float32array[index + 1] = green * exponent;
  71837. float32array[index + 2] = blue * exponent;
  71838. }
  71839. else {
  71840. float32array[index + 0] = 0;
  71841. float32array[index + 1] = 0;
  71842. float32array[index + 2] = 0;
  71843. }
  71844. };
  71845. HDRTools.readStringLine = function (uint8array, startIndex) {
  71846. var line = "";
  71847. var character = "";
  71848. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71849. character = String.fromCharCode(uint8array[i]);
  71850. if (character == "\n") {
  71851. break;
  71852. }
  71853. line += character;
  71854. }
  71855. return line;
  71856. };
  71857. /**
  71858. * Reads header information from an RGBE texture stored in a native array.
  71859. * More information on this format are available here:
  71860. * https://en.wikipedia.org/wiki/RGBE_image_format
  71861. *
  71862. * @param uint8array The binary file stored in native array.
  71863. * @return The header information.
  71864. */
  71865. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71866. var height = 0;
  71867. var width = 0;
  71868. var line = this.readStringLine(uint8array, 0);
  71869. if (line[0] != '#' || line[1] != '?') {
  71870. throw "Bad HDR Format.";
  71871. }
  71872. var endOfHeader = false;
  71873. var findFormat = false;
  71874. var lineIndex = 0;
  71875. do {
  71876. lineIndex += (line.length + 1);
  71877. line = this.readStringLine(uint8array, lineIndex);
  71878. if (line == "FORMAT=32-bit_rle_rgbe") {
  71879. findFormat = true;
  71880. }
  71881. else if (line.length == 0) {
  71882. endOfHeader = true;
  71883. }
  71884. } while (!endOfHeader);
  71885. if (!findFormat) {
  71886. throw "HDR Bad header format, unsupported FORMAT";
  71887. }
  71888. lineIndex += (line.length + 1);
  71889. line = this.readStringLine(uint8array, lineIndex);
  71890. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71891. var match = sizeRegexp.exec(line);
  71892. // TODO. Support +Y and -X if needed.
  71893. if (!match || match.length < 3) {
  71894. throw "HDR Bad header format, no size";
  71895. }
  71896. width = parseInt(match[2]);
  71897. height = parseInt(match[1]);
  71898. if (width < 8 || width > 0x7fff) {
  71899. throw "HDR Bad header format, unsupported size";
  71900. }
  71901. lineIndex += (line.length + 1);
  71902. return {
  71903. height: height,
  71904. width: width,
  71905. dataPosition: lineIndex
  71906. };
  71907. };
  71908. /**
  71909. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71910. * This RGBE texture needs to store the information as a panorama.
  71911. *
  71912. * More information on this format are available here:
  71913. * https://en.wikipedia.org/wiki/RGBE_image_format
  71914. *
  71915. * @param buffer The binary file stored in an array buffer.
  71916. * @param size The expected size of the extracted cubemap.
  71917. * @return The Cube Map information.
  71918. */
  71919. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71920. var uint8array = new Uint8Array(buffer);
  71921. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71922. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71923. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71924. return cubeMapData;
  71925. };
  71926. /**
  71927. * Returns the pixels data extracted from an RGBE texture.
  71928. * This pixels will be stored left to right up to down in the R G B order in one array.
  71929. *
  71930. * More information on this format are available here:
  71931. * https://en.wikipedia.org/wiki/RGBE_image_format
  71932. *
  71933. * @param uint8array The binary file stored in an array buffer.
  71934. * @param hdrInfo The header information of the file.
  71935. * @return The pixels data in RGB right to left up to down order.
  71936. */
  71937. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71938. // Keep for multi format supports.
  71939. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71940. };
  71941. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71942. var num_scanlines = hdrInfo.height;
  71943. var scanline_width = hdrInfo.width;
  71944. var a, b, c, d, count;
  71945. var dataIndex = hdrInfo.dataPosition;
  71946. var index = 0, endIndex = 0, i = 0;
  71947. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71948. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71949. // 3 channels of 4 bytes per pixel in float.
  71950. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71951. var resultArray = new Float32Array(resultBuffer);
  71952. // read in each successive scanline
  71953. while (num_scanlines > 0) {
  71954. a = uint8array[dataIndex++];
  71955. b = uint8array[dataIndex++];
  71956. c = uint8array[dataIndex++];
  71957. d = uint8array[dataIndex++];
  71958. if (a != 2 || b != 2 || (c & 0x80)) {
  71959. // this file is not run length encoded
  71960. throw "HDR Bad header format, not RLE";
  71961. }
  71962. if (((c << 8) | d) != scanline_width) {
  71963. throw "HDR Bad header format, wrong scan line width";
  71964. }
  71965. index = 0;
  71966. // read each of the four channels for the scanline into the buffer
  71967. for (i = 0; i < 4; i++) {
  71968. endIndex = (i + 1) * scanline_width;
  71969. while (index < endIndex) {
  71970. a = uint8array[dataIndex++];
  71971. b = uint8array[dataIndex++];
  71972. if (a > 128) {
  71973. // a run of the same value
  71974. count = a - 128;
  71975. if ((count == 0) || (count > endIndex - index)) {
  71976. throw "HDR Bad Format, bad scanline data (run)";
  71977. }
  71978. while (count-- > 0) {
  71979. scanLineArray[index++] = b;
  71980. }
  71981. }
  71982. else {
  71983. // a non-run
  71984. count = a;
  71985. if ((count == 0) || (count > endIndex - index)) {
  71986. throw "HDR Bad Format, bad scanline data (non-run)";
  71987. }
  71988. scanLineArray[index++] = b;
  71989. if (--count > 0) {
  71990. for (var j = 0; j < count; j++) {
  71991. scanLineArray[index++] = uint8array[dataIndex++];
  71992. }
  71993. }
  71994. }
  71995. }
  71996. }
  71997. // now convert data from buffer into floats
  71998. for (i = 0; i < scanline_width; i++) {
  71999. a = scanLineArray[i];
  72000. b = scanLineArray[i + scanline_width];
  72001. c = scanLineArray[i + 2 * scanline_width];
  72002. d = scanLineArray[i + 3 * scanline_width];
  72003. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72004. }
  72005. num_scanlines--;
  72006. }
  72007. return resultArray;
  72008. };
  72009. return HDRTools;
  72010. }());
  72011. BABYLON.HDRTools = HDRTools;
  72012. })(BABYLON || (BABYLON = {}));
  72013. //# sourceMappingURL=babylon.hdr.js.map
  72014. var BABYLON;
  72015. (function (BABYLON) {
  72016. /**
  72017. * This represents a texture coming from an HDR input.
  72018. *
  72019. * The only supported format is currently panorama picture stored in RGBE format.
  72020. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72021. */
  72022. var HDRCubeTexture = /** @class */ (function (_super) {
  72023. __extends(HDRCubeTexture, _super);
  72024. /**
  72025. * Instantiates an HDRTexture from the following parameters.
  72026. *
  72027. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72028. * @param scene The scene the texture will be used in
  72029. * @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.
  72030. * @param noMipmap Forces to not generate the mipmap if true
  72031. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72032. * @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)
  72033. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72034. */
  72035. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72036. if (noMipmap === void 0) { noMipmap = false; }
  72037. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72038. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72039. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72040. if (onLoad === void 0) { onLoad = null; }
  72041. if (onError === void 0) { onError = null; }
  72042. var _this = _super.call(this, scene) || this;
  72043. _this._useInGammaSpace = false;
  72044. _this._generateHarmonics = true;
  72045. _this._isBABYLONPreprocessed = false;
  72046. _this._onLoad = null;
  72047. _this._onError = null;
  72048. /**
  72049. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72050. */
  72051. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72052. /**
  72053. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72054. * This is usefull at run time to apply the good shader.
  72055. */
  72056. _this.isPMREM = false;
  72057. _this._isBlocking = true;
  72058. /**
  72059. * Gets or sets the center of the bounding box associated with the cube texture
  72060. * It must define where the camera used to render the texture was set
  72061. */
  72062. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72063. if (!url) {
  72064. return _this;
  72065. }
  72066. _this.name = url;
  72067. _this.url = url;
  72068. _this.hasAlpha = false;
  72069. _this.isCube = true;
  72070. _this._textureMatrix = BABYLON.Matrix.Identity();
  72071. _this._onLoad = onLoad;
  72072. _this._onError = onError;
  72073. _this.gammaSpace = false;
  72074. var caps = scene.getEngine().getCaps();
  72075. if (size) {
  72076. _this._isBABYLONPreprocessed = false;
  72077. _this._noMipmap = noMipmap;
  72078. _this._size = size;
  72079. _this._useInGammaSpace = useInGammaSpace;
  72080. _this._usePMREMGenerator = usePMREMGenerator &&
  72081. caps.textureLOD &&
  72082. caps.textureFloat &&
  72083. !_this._useInGammaSpace;
  72084. }
  72085. else {
  72086. _this._isBABYLONPreprocessed = true;
  72087. _this._noMipmap = false;
  72088. _this._useInGammaSpace = false;
  72089. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72090. !_this._useInGammaSpace;
  72091. }
  72092. _this.isPMREM = _this._usePMREMGenerator;
  72093. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72094. if (!_this._texture) {
  72095. if (!scene.useDelayedTextureLoading) {
  72096. _this.loadTexture();
  72097. }
  72098. else {
  72099. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72100. }
  72101. }
  72102. return _this;
  72103. }
  72104. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72105. /**
  72106. * Gets wether or not the texture is blocking during loading.
  72107. */
  72108. get: function () {
  72109. return this._isBlocking;
  72110. },
  72111. /**
  72112. * Sets wether or not the texture is blocking during loading.
  72113. */
  72114. set: function (value) {
  72115. this._isBlocking = value;
  72116. },
  72117. enumerable: true,
  72118. configurable: true
  72119. });
  72120. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72121. get: function () {
  72122. return this._boundingBoxSize;
  72123. },
  72124. /**
  72125. * Gets or sets the size of the bounding box associated with the cube texture
  72126. * When defined, the cubemap will switch to local mode
  72127. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72128. * @example https://www.babylonjs-playground.com/#RNASML
  72129. */
  72130. set: function (value) {
  72131. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72132. return;
  72133. }
  72134. this._boundingBoxSize = value;
  72135. var scene = this.getScene();
  72136. if (scene) {
  72137. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72138. }
  72139. },
  72140. enumerable: true,
  72141. configurable: true
  72142. });
  72143. /**
  72144. * Occurs when the file is a preprocessed .babylon.hdr file.
  72145. */
  72146. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72147. var _this = this;
  72148. var mipLevels = 0;
  72149. var floatArrayView = null;
  72150. var scene = this.getScene();
  72151. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72152. var mips = new Array();
  72153. if (!floatArrayView) {
  72154. return mips;
  72155. }
  72156. var startIndex = 30;
  72157. for (var level = 0; level < mipLevels; level++) {
  72158. mips.push([]);
  72159. // Fill each pixel of the mip level.
  72160. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72161. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72162. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72163. mips[level].push(faceData);
  72164. startIndex += faceSize;
  72165. }
  72166. }
  72167. return mips;
  72168. } : null;
  72169. var callback = function (buffer) {
  72170. var scene = _this.getScene();
  72171. if (!scene) {
  72172. return null;
  72173. }
  72174. // Create Native Array Views
  72175. var intArrayView = new Int32Array(buffer);
  72176. floatArrayView = new Float32Array(buffer);
  72177. // Fill header.
  72178. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72179. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72180. // Update Texture Information.
  72181. if (!_this._texture) {
  72182. return null;
  72183. }
  72184. _this._texture.updateSize(_this._size, _this._size);
  72185. // Fill polynomial information.
  72186. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72187. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72188. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72189. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72190. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72191. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72192. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72193. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72194. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72195. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72196. _this.sphericalPolynomial = sphericalPolynomial;
  72197. // Fill pixel data.
  72198. mipLevels = intArrayView[29]; // Number of mip levels.
  72199. var startIndex = 30;
  72200. var data = [];
  72201. var faceSize = Math.pow(_this._size, 2) * 3;
  72202. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72203. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72204. startIndex += faceSize;
  72205. }
  72206. var results = [];
  72207. var byteArray = null;
  72208. // Push each faces.
  72209. for (var k = 0; k < 6; k++) {
  72210. var dataFace = null;
  72211. // To be deprecated.
  72212. if (version === 1) {
  72213. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72214. dataFace = data[j];
  72215. }
  72216. // If special cases.
  72217. if (!mipmapGenerator && dataFace) {
  72218. if (!scene.getEngine().getCaps().textureFloat) {
  72219. // 3 channels of 1 bytes per pixel in bytes.
  72220. var byteBuffer = new ArrayBuffer(faceSize);
  72221. byteArray = new Uint8Array(byteBuffer);
  72222. }
  72223. for (var i = 0; i < _this._size * _this._size; i++) {
  72224. // Put in gamma space if requested.
  72225. if (_this._useInGammaSpace) {
  72226. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72227. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72228. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72229. }
  72230. // Convert to int texture for fallback.
  72231. if (byteArray) {
  72232. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72233. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72234. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72235. // May use luminance instead if the result is not accurate.
  72236. var max = Math.max(Math.max(r, g), b);
  72237. if (max > 255) {
  72238. var scale = 255 / max;
  72239. r *= scale;
  72240. g *= scale;
  72241. b *= scale;
  72242. }
  72243. byteArray[(i * 3) + 0] = r;
  72244. byteArray[(i * 3) + 1] = g;
  72245. byteArray[(i * 3) + 2] = b;
  72246. }
  72247. }
  72248. }
  72249. // Fill the array accordingly.
  72250. if (byteArray) {
  72251. results.push(byteArray);
  72252. }
  72253. else {
  72254. results.push(dataFace);
  72255. }
  72256. }
  72257. return results;
  72258. };
  72259. if (scene) {
  72260. 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);
  72261. }
  72262. };
  72263. /**
  72264. * Occurs when the file is raw .hdr file.
  72265. */
  72266. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72267. var _this = this;
  72268. var callback = function (buffer) {
  72269. var scene = _this.getScene();
  72270. if (!scene) {
  72271. return null;
  72272. }
  72273. // Extract the raw linear data.
  72274. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72275. // Generate harmonics if needed.
  72276. if (_this._generateHarmonics) {
  72277. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72278. _this.sphericalPolynomial = sphericalPolynomial;
  72279. }
  72280. var results = [];
  72281. var byteArray = null;
  72282. // Push each faces.
  72283. for (var j = 0; j < 6; j++) {
  72284. // Create uintarray fallback.
  72285. if (!scene.getEngine().getCaps().textureFloat) {
  72286. // 3 channels of 1 bytes per pixel in bytes.
  72287. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72288. byteArray = new Uint8Array(byteBuffer);
  72289. }
  72290. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72291. // If special cases.
  72292. if (_this._useInGammaSpace || byteArray) {
  72293. for (var i = 0; i < _this._size * _this._size; i++) {
  72294. // Put in gamma space if requested.
  72295. if (_this._useInGammaSpace) {
  72296. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72297. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72298. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72299. }
  72300. // Convert to int texture for fallback.
  72301. if (byteArray) {
  72302. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72303. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72304. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72305. // May use luminance instead if the result is not accurate.
  72306. var max = Math.max(Math.max(r, g), b);
  72307. if (max > 255) {
  72308. var scale = 255 / max;
  72309. r *= scale;
  72310. g *= scale;
  72311. b *= scale;
  72312. }
  72313. byteArray[(i * 3) + 0] = r;
  72314. byteArray[(i * 3) + 1] = g;
  72315. byteArray[(i * 3) + 2] = b;
  72316. }
  72317. }
  72318. }
  72319. if (byteArray) {
  72320. results.push(byteArray);
  72321. }
  72322. else {
  72323. results.push(dataFace);
  72324. }
  72325. }
  72326. return results;
  72327. };
  72328. var mipmapGenerator = null;
  72329. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72330. // if (!this._noMipmap &&
  72331. // this._usePMREMGenerator) {
  72332. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72333. // // Custom setup of the generator matching with the PBR shader values.
  72334. // var generator = new BABYLON.PMREMGenerator(data,
  72335. // this._size,
  72336. // this._size,
  72337. // 0,
  72338. // 3,
  72339. // this.getScene().getEngine().getCaps().textureFloat,
  72340. // 2048,
  72341. // 0.25,
  72342. // false,
  72343. // true);
  72344. // return generator.filterCubeMap();
  72345. // };
  72346. // }
  72347. var scene = this.getScene();
  72348. if (scene) {
  72349. 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);
  72350. }
  72351. };
  72352. /**
  72353. * Starts the loading process of the texture.
  72354. */
  72355. HDRCubeTexture.prototype.loadTexture = function () {
  72356. if (this._isBABYLONPreprocessed) {
  72357. this.loadBabylonTexture();
  72358. }
  72359. else {
  72360. this.loadHDRTexture();
  72361. }
  72362. };
  72363. HDRCubeTexture.prototype.clone = function () {
  72364. var scene = this.getScene();
  72365. if (!scene) {
  72366. return this;
  72367. }
  72368. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72369. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72370. // Base texture
  72371. newTexture.level = this.level;
  72372. newTexture.wrapU = this.wrapU;
  72373. newTexture.wrapV = this.wrapV;
  72374. newTexture.coordinatesIndex = this.coordinatesIndex;
  72375. newTexture.coordinatesMode = this.coordinatesMode;
  72376. return newTexture;
  72377. };
  72378. // Methods
  72379. HDRCubeTexture.prototype.delayLoad = function () {
  72380. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72381. return;
  72382. }
  72383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72384. this._texture = this._getFromCache(this.url, this._noMipmap);
  72385. if (!this._texture) {
  72386. this.loadTexture();
  72387. }
  72388. };
  72389. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72390. return this._textureMatrix;
  72391. };
  72392. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72393. this._textureMatrix = value;
  72394. };
  72395. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72396. var texture = null;
  72397. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72398. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72399. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72400. texture.name = parsedTexture.name;
  72401. texture.hasAlpha = parsedTexture.hasAlpha;
  72402. texture.level = parsedTexture.level;
  72403. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72404. texture.isBlocking = parsedTexture.isBlocking;
  72405. }
  72406. if (texture) {
  72407. if (parsedTexture.boundingBoxPosition) {
  72408. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72409. }
  72410. if (parsedTexture.boundingBoxSize) {
  72411. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72412. }
  72413. }
  72414. return texture;
  72415. };
  72416. HDRCubeTexture.prototype.serialize = function () {
  72417. if (!this.name) {
  72418. return null;
  72419. }
  72420. var serializationObject = {};
  72421. serializationObject.name = this.name;
  72422. serializationObject.hasAlpha = this.hasAlpha;
  72423. serializationObject.isCube = true;
  72424. serializationObject.level = this.level;
  72425. serializationObject.size = this._size;
  72426. serializationObject.coordinatesMode = this.coordinatesMode;
  72427. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72428. serializationObject.generateHarmonics = this._generateHarmonics;
  72429. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72430. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72431. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72432. serializationObject.noMipmap = this._noMipmap;
  72433. serializationObject.isBlocking = this._isBlocking;
  72434. return serializationObject;
  72435. };
  72436. /**
  72437. * Saves as a file the data contained in the texture in a binary format.
  72438. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72439. * as the spherical used in the lighting.
  72440. * @param url The HDR file url.
  72441. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72442. * @param onError Method called if any error happens during download.
  72443. * @return The packed binary data.
  72444. */
  72445. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72446. if (onError === void 0) { onError = null; }
  72447. var callback = function (buffer) {
  72448. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72449. // Returns a URL you can use as a href.
  72450. var objUrl = window.URL.createObjectURL(data);
  72451. // Simulates a link to it and click to dowload.
  72452. var a = document.createElement("a");
  72453. document.body.appendChild(a);
  72454. a.style.display = "none";
  72455. a.href = objUrl;
  72456. a.download = "envmap.babylon.hdr";
  72457. a.click();
  72458. };
  72459. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72460. };
  72461. /**
  72462. * Serializes the data contained in the texture in a binary format.
  72463. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72464. * as the spherical used in the lighting.
  72465. * @param url The HDR file url.
  72466. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72467. * @param onError Method called if any error happens during download.
  72468. * @return The packed binary data.
  72469. */
  72470. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72471. if (onError === void 0) { onError = null; }
  72472. // Needs the url tho create the texture.
  72473. if (!url) {
  72474. return;
  72475. }
  72476. // Check Power of two size.
  72477. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72478. return;
  72479. }
  72480. // Coming Back in 3.x.
  72481. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72482. };
  72483. HDRCubeTexture._facesMapping = [
  72484. "right",
  72485. "left",
  72486. "up",
  72487. "down",
  72488. "front",
  72489. "back"
  72490. ];
  72491. return HDRCubeTexture;
  72492. }(BABYLON.BaseTexture));
  72493. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72494. })(BABYLON || (BABYLON = {}));
  72495. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72496. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72497. // Huge respect for a such great lib.
  72498. // Earcut license:
  72499. // Copyright (c) 2016, Mapbox
  72500. //
  72501. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72502. // with or without fee is hereby granted, provided that the above copyright notice
  72503. // and this permission notice appear in all copies.
  72504. //
  72505. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72506. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72507. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72508. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72509. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72510. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72511. // THIS SOFTWARE.
  72512. var Earcut;
  72513. (function (Earcut) {
  72514. /**
  72515. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72516. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72517. * @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).
  72518. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72519. */
  72520. function earcut(data, holeIndices, dim) {
  72521. dim = dim || 2;
  72522. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72523. if (!outerNode)
  72524. return triangles;
  72525. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72526. if (hasHoles)
  72527. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72528. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72529. if (data.length > 80 * dim) {
  72530. minX = maxX = data[0];
  72531. minY = maxY = data[1];
  72532. for (var i = dim; i < outerLen; i += dim) {
  72533. x = data[i];
  72534. y = data[i + 1];
  72535. if (x < minX)
  72536. minX = x;
  72537. if (y < minY)
  72538. minY = y;
  72539. if (x > maxX)
  72540. maxX = x;
  72541. if (y > maxY)
  72542. maxY = y;
  72543. }
  72544. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72545. size = Math.max(maxX - minX, maxY - minY);
  72546. }
  72547. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72548. return triangles;
  72549. }
  72550. Earcut.earcut = earcut;
  72551. var Node = /** @class */ (function () {
  72552. function Node(i, x, y) {
  72553. this.i = i;
  72554. this.x = x;
  72555. this.y = y;
  72556. this.prev = null;
  72557. this.next = null;
  72558. this.z = null;
  72559. this.prevZ = null;
  72560. this.nextZ = null;
  72561. this.steiner = false;
  72562. }
  72563. return Node;
  72564. }());
  72565. // create a circular doubly linked list from polygon points in the specified winding order
  72566. function linkedList(data, start, end, dim, clockwise) {
  72567. var i, last = null;
  72568. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72569. for (i = start; i < end; i += dim)
  72570. last = insertNode(i, data[i], data[i + 1], last);
  72571. }
  72572. else {
  72573. for (i = end - dim; i >= start; i -= dim)
  72574. last = insertNode(i, data[i], data[i + 1], last);
  72575. }
  72576. if (last && equals(last, last.next)) {
  72577. removeNode(last);
  72578. last = last.next;
  72579. }
  72580. return last;
  72581. }
  72582. // eliminate colinear or duplicate points
  72583. function filterPoints(start, end) {
  72584. if (!start)
  72585. return start;
  72586. if (!end)
  72587. end = start;
  72588. var p = start, again;
  72589. do {
  72590. again = false;
  72591. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72592. removeNode(p);
  72593. p = end = p.prev;
  72594. if (p === p.next)
  72595. return undefined;
  72596. again = true;
  72597. }
  72598. else {
  72599. p = p.next;
  72600. }
  72601. } while (again || p !== end);
  72602. return end;
  72603. }
  72604. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72605. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72606. if (!ear)
  72607. return;
  72608. // interlink polygon nodes in z-order
  72609. if (!pass && size)
  72610. indexCurve(ear, minX, minY, size);
  72611. var stop = ear, prev, next;
  72612. // iterate through ears, slicing them one by one
  72613. while (ear.prev !== ear.next) {
  72614. prev = ear.prev;
  72615. next = ear.next;
  72616. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72617. // cut off the triangle
  72618. triangles.push(prev.i / dim);
  72619. triangles.push(ear.i / dim);
  72620. triangles.push(next.i / dim);
  72621. removeNode(ear);
  72622. // skipping the next vertice leads to less sliver triangles
  72623. ear = next.next;
  72624. stop = next.next;
  72625. continue;
  72626. }
  72627. ear = next;
  72628. // if we looped through the whole remaining polygon and can't find any more ears
  72629. if (ear === stop) {
  72630. // try filtering points and slicing again
  72631. if (!pass) {
  72632. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72633. // if this didn't work, try curing all small self-intersections locally
  72634. }
  72635. else if (pass === 1) {
  72636. ear = cureLocalIntersections(ear, triangles, dim);
  72637. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72638. // as a last resort, try splitting the remaining polygon into two
  72639. }
  72640. else if (pass === 2) {
  72641. splitEarcut(ear, triangles, dim, minX, minY, size);
  72642. }
  72643. break;
  72644. }
  72645. }
  72646. }
  72647. // check whether a polygon node forms a valid ear with adjacent nodes
  72648. function isEar(ear) {
  72649. var a = ear.prev, b = ear, c = ear.next;
  72650. if (area(a, b, c) >= 0)
  72651. return false; // reflex, can't be an ear
  72652. // now make sure we don't have other points inside the potential ear
  72653. var p = ear.next.next;
  72654. while (p !== ear.prev) {
  72655. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72656. area(p.prev, p, p.next) >= 0)
  72657. return false;
  72658. p = p.next;
  72659. }
  72660. return true;
  72661. }
  72662. function isEarHashed(ear, minX, minY, size) {
  72663. var a = ear.prev, b = ear, c = ear.next;
  72664. if (area(a, b, c) >= 0)
  72665. return false; // reflex, can't be an ear
  72666. // triangle bbox; min & max are calculated like this for speed
  72667. 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);
  72668. // z-order range for the current triangle bbox;
  72669. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72670. // first look for points inside the triangle in increasing z-order
  72671. var p = ear.nextZ;
  72672. while (p && p.z <= maxZ) {
  72673. if (p !== ear.prev &&
  72674. p !== ear.next &&
  72675. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72676. area(p.prev, p, p.next) >= 0)
  72677. return false;
  72678. p = p.nextZ;
  72679. }
  72680. // then look for points in decreasing z-order
  72681. p = ear.prevZ;
  72682. while (p && p.z >= minZ) {
  72683. if (p !== ear.prev &&
  72684. p !== ear.next &&
  72685. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72686. area(p.prev, p, p.next) >= 0)
  72687. return false;
  72688. p = p.prevZ;
  72689. }
  72690. return true;
  72691. }
  72692. // go through all polygon nodes and cure small local self-intersections
  72693. function cureLocalIntersections(start, triangles, dim) {
  72694. var p = start;
  72695. do {
  72696. var a = p.prev, b = p.next.next;
  72697. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  72698. triangles.push(a.i / dim);
  72699. triangles.push(p.i / dim);
  72700. triangles.push(b.i / dim);
  72701. // remove two nodes involved
  72702. removeNode(p);
  72703. removeNode(p.next);
  72704. p = start = b;
  72705. }
  72706. p = p.next;
  72707. } while (p !== start);
  72708. return p;
  72709. }
  72710. // try splitting polygon into two and triangulate them independently
  72711. function splitEarcut(start, triangles, dim, minX, minY, size) {
  72712. // look for a valid diagonal that divides the polygon into two
  72713. var a = start;
  72714. do {
  72715. var b = a.next.next;
  72716. while (b !== a.prev) {
  72717. if (a.i !== b.i && isValidDiagonal(a, b)) {
  72718. // split the polygon in two by the diagonal
  72719. var c = splitPolygon(a, b);
  72720. // filter colinear points around the cuts
  72721. a = filterPoints(a, a.next);
  72722. c = filterPoints(c, c.next);
  72723. // run earcut on each half
  72724. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  72725. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  72726. return;
  72727. }
  72728. b = b.next;
  72729. }
  72730. a = a.next;
  72731. } while (a !== start);
  72732. }
  72733. // link every hole into the outer loop, producing a single-ring polygon without holes
  72734. function eliminateHoles(data, holeIndices, outerNode, dim) {
  72735. var queue = [], i, len, start, end, list;
  72736. for (i = 0, len = holeIndices.length; i < len; i++) {
  72737. start = holeIndices[i] * dim;
  72738. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72739. list = linkedList(data, start, end, dim, false);
  72740. if (list === list.next)
  72741. list.steiner = true;
  72742. queue.push(getLeftmost(list));
  72743. }
  72744. queue.sort(compareX);
  72745. // process holes from left to right
  72746. for (i = 0; i < queue.length; i++) {
  72747. eliminateHole(queue[i], outerNode);
  72748. outerNode = filterPoints(outerNode, outerNode.next);
  72749. }
  72750. return outerNode;
  72751. }
  72752. function compareX(a, b) {
  72753. return a.x - b.x;
  72754. }
  72755. // find a bridge between vertices that connects hole with an outer ring and and link it
  72756. function eliminateHole(hole, outerNode) {
  72757. outerNode = findHoleBridge(hole, outerNode);
  72758. if (outerNode) {
  72759. var b = splitPolygon(outerNode, hole);
  72760. filterPoints(b, b.next);
  72761. }
  72762. }
  72763. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  72764. function findHoleBridge(hole, outerNode) {
  72765. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  72766. // find a segment intersected by a ray from the hole's leftmost point to the left;
  72767. // segment's endpoint with lesser x will be potential connection point
  72768. do {
  72769. if (hy <= p.y && hy >= p.next.y) {
  72770. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  72771. if (x <= hx && x > qx) {
  72772. qx = x;
  72773. if (x === hx) {
  72774. if (hy === p.y)
  72775. return p;
  72776. if (hy === p.next.y)
  72777. return p.next;
  72778. }
  72779. m = p.x < p.next.x ? p : p.next;
  72780. }
  72781. }
  72782. p = p.next;
  72783. } while (p !== outerNode);
  72784. if (!m)
  72785. return null;
  72786. if (hx === qx)
  72787. return m.prev; // hole touches outer segment; pick lower endpoint
  72788. // look for points inside the triangle of hole point, segment intersection and endpoint;
  72789. // if there are no points found, we have a valid connection;
  72790. // otherwise choose the point of the minimum angle with the ray as connection point
  72791. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  72792. p = m.next;
  72793. while (p !== stop) {
  72794. if (hx >= p.x &&
  72795. p.x >= mx &&
  72796. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  72797. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  72798. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  72799. m = p;
  72800. tanMin = tan;
  72801. }
  72802. }
  72803. p = p.next;
  72804. }
  72805. return m;
  72806. }
  72807. // interlink polygon nodes in z-order
  72808. function indexCurve(start, minX, minY, size) {
  72809. var p = start;
  72810. do {
  72811. if (p.z === null)
  72812. p.z = zOrder(p.x, p.y, minX, minY, size);
  72813. p.prevZ = p.prev;
  72814. p.nextZ = p.next;
  72815. p = p.next;
  72816. } while (p !== start);
  72817. p.prevZ.nextZ = null;
  72818. p.prevZ = null;
  72819. sortLinked(p);
  72820. }
  72821. // Simon Tatham's linked list merge sort algorithm
  72822. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  72823. function sortLinked(list) {
  72824. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  72825. do {
  72826. p = list;
  72827. list = null;
  72828. tail = null;
  72829. numMerges = 0;
  72830. while (p) {
  72831. numMerges++;
  72832. q = p;
  72833. pSize = 0;
  72834. for (i = 0; i < inSize; i++) {
  72835. pSize++;
  72836. q = q.nextZ;
  72837. if (!q)
  72838. break;
  72839. }
  72840. qSize = inSize;
  72841. while (pSize > 0 || (qSize > 0 && q)) {
  72842. if (pSize === 0) {
  72843. e = q;
  72844. q = q.nextZ;
  72845. qSize--;
  72846. }
  72847. else if (qSize === 0 || !q) {
  72848. e = p;
  72849. p = p.nextZ;
  72850. pSize--;
  72851. }
  72852. else if (p.z <= q.z) {
  72853. e = p;
  72854. p = p.nextZ;
  72855. pSize--;
  72856. }
  72857. else {
  72858. e = q;
  72859. q = q.nextZ;
  72860. qSize--;
  72861. }
  72862. if (tail)
  72863. tail.nextZ = e;
  72864. else
  72865. list = e;
  72866. e.prevZ = tail;
  72867. tail = e;
  72868. }
  72869. p = q;
  72870. }
  72871. tail.nextZ = null;
  72872. inSize *= 2;
  72873. } while (numMerges > 1);
  72874. return list;
  72875. }
  72876. // z-order of a point given coords and size of the data bounding box
  72877. function zOrder(x, y, minX, minY, size) {
  72878. // coords are transformed into non-negative 15-bit integer range
  72879. x = 32767 * (x - minX) / size;
  72880. y = 32767 * (y - minY) / size;
  72881. x = (x | (x << 8)) & 0x00FF00FF;
  72882. x = (x | (x << 4)) & 0x0F0F0F0F;
  72883. x = (x | (x << 2)) & 0x33333333;
  72884. x = (x | (x << 1)) & 0x55555555;
  72885. y = (y | (y << 8)) & 0x00FF00FF;
  72886. y = (y | (y << 4)) & 0x0F0F0F0F;
  72887. y = (y | (y << 2)) & 0x33333333;
  72888. y = (y | (y << 1)) & 0x55555555;
  72889. return x | (y << 1);
  72890. }
  72891. // find the leftmost node of a polygon ring
  72892. function getLeftmost(start) {
  72893. var p = start, leftmost = start;
  72894. do {
  72895. if (p.x < leftmost.x)
  72896. leftmost = p;
  72897. p = p.next;
  72898. } while (p !== start);
  72899. return leftmost;
  72900. }
  72901. // check if a point lies within a convex triangle
  72902. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72903. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72904. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72905. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72906. }
  72907. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72908. function isValidDiagonal(a, b) {
  72909. return a.next.i !== b.i &&
  72910. a.prev.i !== b.i &&
  72911. !intersectsPolygon(a, b) &&
  72912. locallyInside(a, b) &&
  72913. locallyInside(b, a) &&
  72914. middleInside(a, b);
  72915. }
  72916. // signed area of a triangle
  72917. function area(p, q, r) {
  72918. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72919. }
  72920. // check if two points are equal
  72921. function equals(p1, p2) {
  72922. return p1.x === p2.x && p1.y === p2.y;
  72923. }
  72924. // check if two segments intersect
  72925. function intersects(p1, q1, p2, q2) {
  72926. if ((equals(p1, q1) && equals(p2, q2)) ||
  72927. (equals(p1, q2) && equals(p2, q1)))
  72928. return true;
  72929. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72930. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72931. }
  72932. // check if a polygon diagonal intersects any polygon segments
  72933. function intersectsPolygon(a, b) {
  72934. var p = a;
  72935. do {
  72936. if (p.i !== a.i &&
  72937. p.next.i !== a.i &&
  72938. p.i !== b.i &&
  72939. p.next.i !== b.i &&
  72940. intersects(p, p.next, a, b))
  72941. return true;
  72942. p = p.next;
  72943. } while (p !== a);
  72944. return false;
  72945. }
  72946. // check if a polygon diagonal is locally inside the polygon
  72947. function locallyInside(a, b) {
  72948. return area(a.prev, a, a.next) < 0
  72949. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72950. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72951. }
  72952. // check if the middle point of a polygon diagonal is inside the polygon
  72953. function middleInside(a, b) {
  72954. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72955. do {
  72956. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72957. inside = !inside;
  72958. p = p.next;
  72959. } while (p !== a);
  72960. return inside;
  72961. }
  72962. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72963. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72964. function splitPolygon(a, b) {
  72965. 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;
  72966. a.next = b;
  72967. b.prev = a;
  72968. a2.next = an;
  72969. an.prev = a2;
  72970. b2.next = a2;
  72971. a2.prev = b2;
  72972. bp.next = b2;
  72973. b2.prev = bp;
  72974. return b2;
  72975. }
  72976. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72977. function insertNode(i, x, y, last) {
  72978. var p = new Node(i, x, y);
  72979. if (!last) {
  72980. p.prev = p;
  72981. p.next = p;
  72982. }
  72983. else {
  72984. p.next = last.next;
  72985. p.prev = last;
  72986. last.next.prev = p;
  72987. last.next = p;
  72988. }
  72989. return p;
  72990. }
  72991. function removeNode(p) {
  72992. p.next.prev = p.prev;
  72993. p.prev.next = p.next;
  72994. if (p.prevZ)
  72995. p.prevZ.nextZ = p.nextZ;
  72996. if (p.nextZ)
  72997. p.nextZ.prevZ = p.prevZ;
  72998. }
  72999. /**
  73000. * return a percentage difference between the polygon area and its triangulation area;
  73001. * used to verify correctness of triangulation
  73002. */
  73003. function deviation(data, holeIndices, dim, triangles) {
  73004. var hasHoles = holeIndices && holeIndices.length;
  73005. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73006. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73007. if (hasHoles) {
  73008. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73009. var start = holeIndices[i] * dim;
  73010. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73011. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73012. }
  73013. }
  73014. var trianglesArea = 0;
  73015. for (i = 0; i < triangles.length; i += 3) {
  73016. var a = triangles[i] * dim;
  73017. var b = triangles[i + 1] * dim;
  73018. var c = triangles[i + 2] * dim;
  73019. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73020. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73021. }
  73022. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73023. }
  73024. Earcut.deviation = deviation;
  73025. ;
  73026. function signedArea(data, start, end, dim) {
  73027. var sum = 0;
  73028. for (var i = start, j = end - dim; i < end; i += dim) {
  73029. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73030. j = i;
  73031. }
  73032. return sum;
  73033. }
  73034. /**
  73035. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73036. */
  73037. function flatten(data) {
  73038. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73039. for (var i = 0; i < data.length; i++) {
  73040. for (var j = 0; j < data[i].length; j++) {
  73041. for (var d = 0; d < dim; d++)
  73042. result.vertices.push(data[i][j][d]);
  73043. }
  73044. if (i > 0) {
  73045. holeIndex += data[i - 1].length;
  73046. result.holes.push(holeIndex);
  73047. }
  73048. }
  73049. return result;
  73050. }
  73051. Earcut.flatten = flatten;
  73052. ;
  73053. })(Earcut || (Earcut = {}));
  73054. //# sourceMappingURL=babylon.earcut.js.map
  73055. var BABYLON;
  73056. (function (BABYLON) {
  73057. var IndexedVector2 = /** @class */ (function (_super) {
  73058. __extends(IndexedVector2, _super);
  73059. function IndexedVector2(original, index) {
  73060. var _this = _super.call(this, original.x, original.y) || this;
  73061. _this.index = index;
  73062. return _this;
  73063. }
  73064. return IndexedVector2;
  73065. }(BABYLON.Vector2));
  73066. var PolygonPoints = /** @class */ (function () {
  73067. function PolygonPoints() {
  73068. this.elements = new Array();
  73069. }
  73070. PolygonPoints.prototype.add = function (originalPoints) {
  73071. var _this = this;
  73072. var result = new Array();
  73073. originalPoints.forEach(function (point) {
  73074. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73075. var newPoint = new IndexedVector2(point, _this.elements.length);
  73076. result.push(newPoint);
  73077. _this.elements.push(newPoint);
  73078. }
  73079. });
  73080. return result;
  73081. };
  73082. PolygonPoints.prototype.computeBounds = function () {
  73083. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73084. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73085. this.elements.forEach(function (point) {
  73086. // x
  73087. if (point.x < lmin.x) {
  73088. lmin.x = point.x;
  73089. }
  73090. else if (point.x > lmax.x) {
  73091. lmax.x = point.x;
  73092. }
  73093. // y
  73094. if (point.y < lmin.y) {
  73095. lmin.y = point.y;
  73096. }
  73097. else if (point.y > lmax.y) {
  73098. lmax.y = point.y;
  73099. }
  73100. });
  73101. return {
  73102. min: lmin,
  73103. max: lmax,
  73104. width: lmax.x - lmin.x,
  73105. height: lmax.y - lmin.y
  73106. };
  73107. };
  73108. return PolygonPoints;
  73109. }());
  73110. var Polygon = /** @class */ (function () {
  73111. function Polygon() {
  73112. }
  73113. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73114. return [
  73115. new BABYLON.Vector2(xmin, ymin),
  73116. new BABYLON.Vector2(xmax, ymin),
  73117. new BABYLON.Vector2(xmax, ymax),
  73118. new BABYLON.Vector2(xmin, ymax)
  73119. ];
  73120. };
  73121. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73122. if (cx === void 0) { cx = 0; }
  73123. if (cy === void 0) { cy = 0; }
  73124. if (numberOfSides === void 0) { numberOfSides = 32; }
  73125. var result = new Array();
  73126. var angle = 0;
  73127. var increment = (Math.PI * 2) / numberOfSides;
  73128. for (var i = 0; i < numberOfSides; i++) {
  73129. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73130. angle -= increment;
  73131. }
  73132. return result;
  73133. };
  73134. Polygon.Parse = function (input) {
  73135. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73136. var i, result = [];
  73137. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73138. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73139. }
  73140. return result;
  73141. };
  73142. Polygon.StartingAt = function (x, y) {
  73143. return BABYLON.Path2.StartingAt(x, y);
  73144. };
  73145. return Polygon;
  73146. }());
  73147. BABYLON.Polygon = Polygon;
  73148. var PolygonMeshBuilder = /** @class */ (function () {
  73149. function PolygonMeshBuilder(name, contours, scene) {
  73150. this._points = new PolygonPoints();
  73151. this._outlinepoints = new PolygonPoints();
  73152. this._holes = new Array();
  73153. this._epoints = new Array();
  73154. this._eholes = new Array();
  73155. this._name = name;
  73156. this._scene = scene;
  73157. var points;
  73158. if (contours instanceof BABYLON.Path2) {
  73159. points = contours.getPoints();
  73160. }
  73161. else {
  73162. points = contours;
  73163. }
  73164. this._addToepoint(points);
  73165. this._points.add(points);
  73166. this._outlinepoints.add(points);
  73167. }
  73168. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73169. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73170. var p = points_1[_i];
  73171. this._epoints.push(p.x, p.y);
  73172. }
  73173. };
  73174. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73175. this._points.add(hole);
  73176. var holepoints = new PolygonPoints();
  73177. holepoints.add(hole);
  73178. this._holes.push(holepoints);
  73179. this._eholes.push(this._epoints.length / 2);
  73180. this._addToepoint(hole);
  73181. return this;
  73182. };
  73183. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73184. var _this = this;
  73185. if (updatable === void 0) { updatable = false; }
  73186. if (depth === void 0) { depth = 0; }
  73187. var result = new BABYLON.Mesh(this._name, this._scene);
  73188. var normals = new Array();
  73189. var positions = new Array();
  73190. var uvs = new Array();
  73191. var bounds = this._points.computeBounds();
  73192. this._points.elements.forEach(function (p) {
  73193. normals.push(0, 1.0, 0);
  73194. positions.push(p.x, 0, p.y);
  73195. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73196. });
  73197. var indices = new Array();
  73198. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73199. for (var i = 0; i < res.length; i++) {
  73200. indices.push(res[i]);
  73201. }
  73202. if (depth > 0) {
  73203. var positionscount = (positions.length / 3); //get the current pointcount
  73204. this._points.elements.forEach(function (p) {
  73205. normals.push(0, -1.0, 0);
  73206. positions.push(p.x, -depth, p.y);
  73207. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73208. });
  73209. var totalCount = indices.length;
  73210. for (var i = 0; i < totalCount; i += 3) {
  73211. var i0 = indices[i + 0];
  73212. var i1 = indices[i + 1];
  73213. var i2 = indices[i + 2];
  73214. indices.push(i2 + positionscount);
  73215. indices.push(i1 + positionscount);
  73216. indices.push(i0 + positionscount);
  73217. }
  73218. //Add the sides
  73219. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73220. this._holes.forEach(function (hole) {
  73221. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73222. });
  73223. }
  73224. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73225. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73226. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73227. result.setIndices(indices);
  73228. return result;
  73229. };
  73230. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73231. var StartIndex = positions.length / 3;
  73232. var ulength = 0;
  73233. for (var i = 0; i < points.elements.length; i++) {
  73234. var p = points.elements[i];
  73235. var p1;
  73236. if ((i + 1) > points.elements.length - 1) {
  73237. p1 = points.elements[0];
  73238. }
  73239. else {
  73240. p1 = points.elements[i + 1];
  73241. }
  73242. positions.push(p.x, 0, p.y);
  73243. positions.push(p.x, -depth, p.y);
  73244. positions.push(p1.x, 0, p1.y);
  73245. positions.push(p1.x, -depth, p1.y);
  73246. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73247. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73248. var v3 = v2.subtract(v1);
  73249. var v4 = new BABYLON.Vector3(0, 1, 0);
  73250. var vn = BABYLON.Vector3.Cross(v3, v4);
  73251. vn = vn.normalize();
  73252. uvs.push(ulength / bounds.width, 0);
  73253. uvs.push(ulength / bounds.width, 1);
  73254. ulength += v3.length();
  73255. uvs.push((ulength / bounds.width), 0);
  73256. uvs.push((ulength / bounds.width), 1);
  73257. if (!flip) {
  73258. normals.push(-vn.x, -vn.y, -vn.z);
  73259. normals.push(-vn.x, -vn.y, -vn.z);
  73260. normals.push(-vn.x, -vn.y, -vn.z);
  73261. normals.push(-vn.x, -vn.y, -vn.z);
  73262. indices.push(StartIndex);
  73263. indices.push(StartIndex + 1);
  73264. indices.push(StartIndex + 2);
  73265. indices.push(StartIndex + 1);
  73266. indices.push(StartIndex + 3);
  73267. indices.push(StartIndex + 2);
  73268. }
  73269. else {
  73270. normals.push(vn.x, vn.y, vn.z);
  73271. normals.push(vn.x, vn.y, vn.z);
  73272. normals.push(vn.x, vn.y, vn.z);
  73273. normals.push(vn.x, vn.y, vn.z);
  73274. indices.push(StartIndex);
  73275. indices.push(StartIndex + 2);
  73276. indices.push(StartIndex + 1);
  73277. indices.push(StartIndex + 1);
  73278. indices.push(StartIndex + 2);
  73279. indices.push(StartIndex + 3);
  73280. }
  73281. StartIndex += 4;
  73282. }
  73283. ;
  73284. };
  73285. return PolygonMeshBuilder;
  73286. }());
  73287. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73288. })(BABYLON || (BABYLON = {}));
  73289. //# sourceMappingURL=babylon.polygonMesh.js.map
  73290. var BABYLON;
  73291. (function (BABYLON) {
  73292. // Unique ID when we import meshes from Babylon to CSG
  73293. var currentCSGMeshId = 0;
  73294. // # class Vertex
  73295. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73296. // one to provide additional features like texture coordinates and vertex
  73297. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73298. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73299. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73300. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73301. // is not used anywhere else.
  73302. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73303. var Vertex = /** @class */ (function () {
  73304. function Vertex(pos, normal, uv) {
  73305. this.pos = pos;
  73306. this.normal = normal;
  73307. this.uv = uv;
  73308. }
  73309. Vertex.prototype.clone = function () {
  73310. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73311. };
  73312. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73313. // orientation of a polygon is flipped.
  73314. Vertex.prototype.flip = function () {
  73315. this.normal = this.normal.scale(-1);
  73316. };
  73317. // Create a new vertex between this vertex and `other` by linearly
  73318. // interpolating all properties using a parameter of `t`. Subclasses should
  73319. // override this to interpolate additional properties.
  73320. Vertex.prototype.interpolate = function (other, t) {
  73321. 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));
  73322. };
  73323. return Vertex;
  73324. }());
  73325. // # class Plane
  73326. // Represents a plane in 3D space.
  73327. var Plane = /** @class */ (function () {
  73328. function Plane(normal, w) {
  73329. this.normal = normal;
  73330. this.w = w;
  73331. }
  73332. Plane.FromPoints = function (a, b, c) {
  73333. var v0 = c.subtract(a);
  73334. var v1 = b.subtract(a);
  73335. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73336. return null;
  73337. }
  73338. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73339. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73340. };
  73341. Plane.prototype.clone = function () {
  73342. return new Plane(this.normal.clone(), this.w);
  73343. };
  73344. Plane.prototype.flip = function () {
  73345. this.normal.scaleInPlace(-1);
  73346. this.w = -this.w;
  73347. };
  73348. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73349. // fragments in the appropriate lists. Coplanar polygons go into either
  73350. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73351. // respect to this plane. Polygons in front or in back of this plane go into
  73352. // either `front` or `back`.
  73353. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73354. var COPLANAR = 0;
  73355. var FRONT = 1;
  73356. var BACK = 2;
  73357. var SPANNING = 3;
  73358. // Classify each point as well as the entire polygon into one of the above
  73359. // four classes.
  73360. var polygonType = 0;
  73361. var types = [];
  73362. var i;
  73363. var t;
  73364. for (i = 0; i < polygon.vertices.length; i++) {
  73365. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73366. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73367. polygonType |= type;
  73368. types.push(type);
  73369. }
  73370. // Put the polygon in the correct list, splitting it when necessary.
  73371. switch (polygonType) {
  73372. case COPLANAR:
  73373. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73374. break;
  73375. case FRONT:
  73376. front.push(polygon);
  73377. break;
  73378. case BACK:
  73379. back.push(polygon);
  73380. break;
  73381. case SPANNING:
  73382. var f = [], b = [];
  73383. for (i = 0; i < polygon.vertices.length; i++) {
  73384. var j = (i + 1) % polygon.vertices.length;
  73385. var ti = types[i], tj = types[j];
  73386. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73387. if (ti !== BACK)
  73388. f.push(vi);
  73389. if (ti !== FRONT)
  73390. b.push(ti !== BACK ? vi.clone() : vi);
  73391. if ((ti | tj) === SPANNING) {
  73392. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73393. var v = vi.interpolate(vj, t);
  73394. f.push(v);
  73395. b.push(v.clone());
  73396. }
  73397. }
  73398. var poly;
  73399. if (f.length >= 3) {
  73400. poly = new Polygon(f, polygon.shared);
  73401. if (poly.plane)
  73402. front.push(poly);
  73403. }
  73404. if (b.length >= 3) {
  73405. poly = new Polygon(b, polygon.shared);
  73406. if (poly.plane)
  73407. back.push(poly);
  73408. }
  73409. break;
  73410. }
  73411. };
  73412. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73413. // point is on the plane.
  73414. Plane.EPSILON = 1e-5;
  73415. return Plane;
  73416. }());
  73417. // # class Polygon
  73418. // Represents a convex polygon. The vertices used to initialize a polygon must
  73419. // be coplanar and form a convex loop.
  73420. //
  73421. // Each convex polygon has a `shared` property, which is shared between all
  73422. // polygons that are clones of each other or were split from the same polygon.
  73423. // This can be used to define per-polygon properties (such as surface color).
  73424. var Polygon = /** @class */ (function () {
  73425. function Polygon(vertices, shared) {
  73426. this.vertices = vertices;
  73427. this.shared = shared;
  73428. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73429. }
  73430. Polygon.prototype.clone = function () {
  73431. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73432. return new Polygon(vertices, this.shared);
  73433. };
  73434. Polygon.prototype.flip = function () {
  73435. this.vertices.reverse().map(function (v) { v.flip(); });
  73436. this.plane.flip();
  73437. };
  73438. return Polygon;
  73439. }());
  73440. // # class Node
  73441. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73442. // by picking a polygon to split along. That polygon (and all other coplanar
  73443. // polygons) are added directly to that node and the other polygons are added to
  73444. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73445. // no distinction between internal and leaf nodes.
  73446. var Node = /** @class */ (function () {
  73447. function Node(polygons) {
  73448. this.plane = null;
  73449. this.front = null;
  73450. this.back = null;
  73451. this.polygons = new Array();
  73452. if (polygons) {
  73453. this.build(polygons);
  73454. }
  73455. }
  73456. Node.prototype.clone = function () {
  73457. var node = new Node();
  73458. node.plane = this.plane && this.plane.clone();
  73459. node.front = this.front && this.front.clone();
  73460. node.back = this.back && this.back.clone();
  73461. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73462. return node;
  73463. };
  73464. // Convert solid space to empty space and empty space to solid space.
  73465. Node.prototype.invert = function () {
  73466. for (var i = 0; i < this.polygons.length; i++) {
  73467. this.polygons[i].flip();
  73468. }
  73469. if (this.plane) {
  73470. this.plane.flip();
  73471. }
  73472. if (this.front) {
  73473. this.front.invert();
  73474. }
  73475. if (this.back) {
  73476. this.back.invert();
  73477. }
  73478. var temp = this.front;
  73479. this.front = this.back;
  73480. this.back = temp;
  73481. };
  73482. // Recursively remove all polygons in `polygons` that are inside this BSP
  73483. // tree.
  73484. Node.prototype.clipPolygons = function (polygons) {
  73485. if (!this.plane)
  73486. return polygons.slice();
  73487. var front = new Array(), back = new Array();
  73488. for (var i = 0; i < polygons.length; i++) {
  73489. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73490. }
  73491. if (this.front) {
  73492. front = this.front.clipPolygons(front);
  73493. }
  73494. if (this.back) {
  73495. back = this.back.clipPolygons(back);
  73496. }
  73497. else {
  73498. back = [];
  73499. }
  73500. return front.concat(back);
  73501. };
  73502. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73503. // `bsp`.
  73504. Node.prototype.clipTo = function (bsp) {
  73505. this.polygons = bsp.clipPolygons(this.polygons);
  73506. if (this.front)
  73507. this.front.clipTo(bsp);
  73508. if (this.back)
  73509. this.back.clipTo(bsp);
  73510. };
  73511. // Return a list of all polygons in this BSP tree.
  73512. Node.prototype.allPolygons = function () {
  73513. var polygons = this.polygons.slice();
  73514. if (this.front)
  73515. polygons = polygons.concat(this.front.allPolygons());
  73516. if (this.back)
  73517. polygons = polygons.concat(this.back.allPolygons());
  73518. return polygons;
  73519. };
  73520. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73521. // new polygons are filtered down to the bottom of the tree and become new
  73522. // nodes there. Each set of polygons is partitioned using the first polygon
  73523. // (no heuristic is used to pick a good split).
  73524. Node.prototype.build = function (polygons) {
  73525. if (!polygons.length)
  73526. return;
  73527. if (!this.plane)
  73528. this.plane = polygons[0].plane.clone();
  73529. var front = new Array(), back = new Array();
  73530. for (var i = 0; i < polygons.length; i++) {
  73531. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73532. }
  73533. if (front.length) {
  73534. if (!this.front)
  73535. this.front = new Node();
  73536. this.front.build(front);
  73537. }
  73538. if (back.length) {
  73539. if (!this.back)
  73540. this.back = new Node();
  73541. this.back.build(back);
  73542. }
  73543. };
  73544. return Node;
  73545. }());
  73546. var CSG = /** @class */ (function () {
  73547. function CSG() {
  73548. this.polygons = new Array();
  73549. }
  73550. // Convert BABYLON.Mesh to BABYLON.CSG
  73551. CSG.FromMesh = function (mesh) {
  73552. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73553. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73554. if (mesh instanceof BABYLON.Mesh) {
  73555. mesh.computeWorldMatrix(true);
  73556. matrix = mesh.getWorldMatrix();
  73557. meshPosition = mesh.position.clone();
  73558. meshRotation = mesh.rotation.clone();
  73559. if (mesh.rotationQuaternion) {
  73560. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73561. }
  73562. meshScaling = mesh.scaling.clone();
  73563. }
  73564. else {
  73565. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73566. }
  73567. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73568. var subMeshes = mesh.subMeshes;
  73569. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73570. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73571. vertices = [];
  73572. for (var j = 0; j < 3; j++) {
  73573. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73574. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73575. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73576. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73577. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73578. vertex = new Vertex(position, normal, uv);
  73579. vertices.push(vertex);
  73580. }
  73581. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73582. // To handle the case of degenerated triangle
  73583. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73584. if (polygon.plane)
  73585. polygons.push(polygon);
  73586. }
  73587. }
  73588. var csg = CSG.FromPolygons(polygons);
  73589. csg.matrix = matrix;
  73590. csg.position = meshPosition;
  73591. csg.rotation = meshRotation;
  73592. csg.scaling = meshScaling;
  73593. csg.rotationQuaternion = meshRotationQuaternion;
  73594. currentCSGMeshId++;
  73595. return csg;
  73596. };
  73597. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73598. CSG.FromPolygons = function (polygons) {
  73599. var csg = new CSG();
  73600. csg.polygons = polygons;
  73601. return csg;
  73602. };
  73603. CSG.prototype.clone = function () {
  73604. var csg = new CSG();
  73605. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73606. csg.copyTransformAttributes(this);
  73607. return csg;
  73608. };
  73609. CSG.prototype.union = function (csg) {
  73610. var a = new Node(this.clone().polygons);
  73611. var b = new Node(csg.clone().polygons);
  73612. a.clipTo(b);
  73613. b.clipTo(a);
  73614. b.invert();
  73615. b.clipTo(a);
  73616. b.invert();
  73617. a.build(b.allPolygons());
  73618. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73619. };
  73620. CSG.prototype.unionInPlace = function (csg) {
  73621. var a = new Node(this.polygons);
  73622. var b = new Node(csg.polygons);
  73623. a.clipTo(b);
  73624. b.clipTo(a);
  73625. b.invert();
  73626. b.clipTo(a);
  73627. b.invert();
  73628. a.build(b.allPolygons());
  73629. this.polygons = a.allPolygons();
  73630. };
  73631. CSG.prototype.subtract = function (csg) {
  73632. var a = new Node(this.clone().polygons);
  73633. var b = new Node(csg.clone().polygons);
  73634. a.invert();
  73635. a.clipTo(b);
  73636. b.clipTo(a);
  73637. b.invert();
  73638. b.clipTo(a);
  73639. b.invert();
  73640. a.build(b.allPolygons());
  73641. a.invert();
  73642. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73643. };
  73644. CSG.prototype.subtractInPlace = function (csg) {
  73645. var a = new Node(this.polygons);
  73646. var b = new Node(csg.polygons);
  73647. a.invert();
  73648. a.clipTo(b);
  73649. b.clipTo(a);
  73650. b.invert();
  73651. b.clipTo(a);
  73652. b.invert();
  73653. a.build(b.allPolygons());
  73654. a.invert();
  73655. this.polygons = a.allPolygons();
  73656. };
  73657. CSG.prototype.intersect = function (csg) {
  73658. var a = new Node(this.clone().polygons);
  73659. var b = new Node(csg.clone().polygons);
  73660. a.invert();
  73661. b.clipTo(a);
  73662. b.invert();
  73663. a.clipTo(b);
  73664. b.clipTo(a);
  73665. a.build(b.allPolygons());
  73666. a.invert();
  73667. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73668. };
  73669. CSG.prototype.intersectInPlace = function (csg) {
  73670. var a = new Node(this.polygons);
  73671. var b = new Node(csg.polygons);
  73672. a.invert();
  73673. b.clipTo(a);
  73674. b.invert();
  73675. a.clipTo(b);
  73676. b.clipTo(a);
  73677. a.build(b.allPolygons());
  73678. a.invert();
  73679. this.polygons = a.allPolygons();
  73680. };
  73681. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73682. // not modified.
  73683. CSG.prototype.inverse = function () {
  73684. var csg = this.clone();
  73685. csg.inverseInPlace();
  73686. return csg;
  73687. };
  73688. CSG.prototype.inverseInPlace = function () {
  73689. this.polygons.map(function (p) { p.flip(); });
  73690. };
  73691. // This is used to keep meshes transformations so they can be restored
  73692. // when we build back a Babylon Mesh
  73693. // NB : All CSG operations are performed in world coordinates
  73694. CSG.prototype.copyTransformAttributes = function (csg) {
  73695. this.matrix = csg.matrix;
  73696. this.position = csg.position;
  73697. this.rotation = csg.rotation;
  73698. this.scaling = csg.scaling;
  73699. this.rotationQuaternion = csg.rotationQuaternion;
  73700. return this;
  73701. };
  73702. // Build Raw mesh from CSG
  73703. // Coordinates here are in world space
  73704. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  73705. var matrix = this.matrix.clone();
  73706. matrix.invert();
  73707. 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;
  73708. if (keepSubMeshes) {
  73709. // Sort Polygons, since subMeshes are indices range
  73710. polygons.sort(function (a, b) {
  73711. if (a.shared.meshId === b.shared.meshId) {
  73712. return a.shared.subMeshId - b.shared.subMeshId;
  73713. }
  73714. else {
  73715. return a.shared.meshId - b.shared.meshId;
  73716. }
  73717. });
  73718. }
  73719. for (var i = 0, il = polygons.length; i < il; i++) {
  73720. polygon = polygons[i];
  73721. // Building SubMeshes
  73722. if (!subMesh_dict[polygon.shared.meshId]) {
  73723. subMesh_dict[polygon.shared.meshId] = {};
  73724. }
  73725. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  73726. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  73727. indexStart: +Infinity,
  73728. indexEnd: -Infinity,
  73729. materialIndex: polygon.shared.materialIndex
  73730. };
  73731. }
  73732. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  73733. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  73734. polygonIndices[0] = 0;
  73735. polygonIndices[1] = j - 1;
  73736. polygonIndices[2] = j;
  73737. for (var k = 0; k < 3; k++) {
  73738. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  73739. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  73740. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  73741. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  73742. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  73743. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  73744. // Check if 2 points can be merged
  73745. if (!(typeof vertex_idx !== 'undefined' &&
  73746. normals[vertex_idx * 3] === localNormal.x &&
  73747. normals[vertex_idx * 3 + 1] === localNormal.y &&
  73748. normals[vertex_idx * 3 + 2] === localNormal.z &&
  73749. uvs[vertex_idx * 2] === uv.x &&
  73750. uvs[vertex_idx * 2 + 1] === uv.y)) {
  73751. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  73752. uvs.push(uv.x, uv.y);
  73753. normals.push(normal.x, normal.y, normal.z);
  73754. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  73755. }
  73756. indices.push(vertex_idx);
  73757. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  73758. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  73759. currentIndex++;
  73760. }
  73761. }
  73762. }
  73763. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  73764. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  73765. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  73766. mesh.setIndices(indices, null);
  73767. if (keepSubMeshes) {
  73768. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  73769. var materialIndexOffset = 0, materialMaxIndex;
  73770. mesh.subMeshes = new Array();
  73771. for (var m in subMesh_dict) {
  73772. materialMaxIndex = -1;
  73773. for (var sm in subMesh_dict[m]) {
  73774. subMesh_obj = subMesh_dict[m][sm];
  73775. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  73776. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  73777. }
  73778. materialIndexOffset += ++materialMaxIndex;
  73779. }
  73780. }
  73781. return mesh;
  73782. };
  73783. // Build Mesh from CSG taking material and transforms into account
  73784. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  73785. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  73786. mesh.material = material;
  73787. mesh.position.copyFrom(this.position);
  73788. mesh.rotation.copyFrom(this.rotation);
  73789. if (this.rotationQuaternion) {
  73790. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  73791. }
  73792. mesh.scaling.copyFrom(this.scaling);
  73793. mesh.computeWorldMatrix(true);
  73794. return mesh;
  73795. };
  73796. return CSG;
  73797. }());
  73798. BABYLON.CSG = CSG;
  73799. })(BABYLON || (BABYLON = {}));
  73800. //# sourceMappingURL=babylon.csg.js.map
  73801. var BABYLON;
  73802. (function (BABYLON) {
  73803. var LensFlare = /** @class */ (function () {
  73804. function LensFlare(size, position, color, imgUrl, system) {
  73805. this.size = size;
  73806. this.position = position;
  73807. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73808. this.color = color || new BABYLON.Color3(1, 1, 1);
  73809. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  73810. this._system = system;
  73811. system.lensFlares.push(this);
  73812. }
  73813. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  73814. return new LensFlare(size, position, color, imgUrl, system);
  73815. };
  73816. LensFlare.prototype.dispose = function () {
  73817. if (this.texture) {
  73818. this.texture.dispose();
  73819. }
  73820. // Remove from scene
  73821. var index = this._system.lensFlares.indexOf(this);
  73822. this._system.lensFlares.splice(index, 1);
  73823. };
  73824. ;
  73825. return LensFlare;
  73826. }());
  73827. BABYLON.LensFlare = LensFlare;
  73828. })(BABYLON || (BABYLON = {}));
  73829. //# sourceMappingURL=babylon.lensFlare.js.map
  73830. var BABYLON;
  73831. (function (BABYLON) {
  73832. var LensFlareSystem = /** @class */ (function () {
  73833. function LensFlareSystem(name, emitter, scene) {
  73834. this.name = name;
  73835. this.lensFlares = new Array();
  73836. this.borderLimit = 300;
  73837. this.viewportBorder = 0;
  73838. this.layerMask = 0x0FFFFFFF;
  73839. this._vertexBuffers = {};
  73840. this._isEnabled = true;
  73841. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73842. this._emitter = emitter;
  73843. this.id = name;
  73844. scene.lensFlareSystems.push(this);
  73845. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73846. var engine = scene.getEngine();
  73847. // VBO
  73848. var vertices = [];
  73849. vertices.push(1, 1);
  73850. vertices.push(-1, 1);
  73851. vertices.push(-1, -1);
  73852. vertices.push(1, -1);
  73853. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73854. // Indices
  73855. var indices = [];
  73856. indices.push(0);
  73857. indices.push(1);
  73858. indices.push(2);
  73859. indices.push(0);
  73860. indices.push(2);
  73861. indices.push(3);
  73862. this._indexBuffer = engine.createIndexBuffer(indices);
  73863. // Effects
  73864. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73865. }
  73866. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73867. get: function () {
  73868. return this._isEnabled;
  73869. },
  73870. set: function (value) {
  73871. this._isEnabled = value;
  73872. },
  73873. enumerable: true,
  73874. configurable: true
  73875. });
  73876. LensFlareSystem.prototype.getScene = function () {
  73877. return this._scene;
  73878. };
  73879. LensFlareSystem.prototype.getEmitter = function () {
  73880. return this._emitter;
  73881. };
  73882. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73883. this._emitter = newEmitter;
  73884. };
  73885. LensFlareSystem.prototype.getEmitterPosition = function () {
  73886. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73887. };
  73888. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73889. var position = this.getEmitterPosition();
  73890. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73891. this._positionX = position.x;
  73892. this._positionY = position.y;
  73893. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73894. if (this.viewportBorder > 0) {
  73895. globalViewport.x -= this.viewportBorder;
  73896. globalViewport.y -= this.viewportBorder;
  73897. globalViewport.width += this.viewportBorder * 2;
  73898. globalViewport.height += this.viewportBorder * 2;
  73899. position.x += this.viewportBorder;
  73900. position.y += this.viewportBorder;
  73901. this._positionX += this.viewportBorder;
  73902. this._positionY += this.viewportBorder;
  73903. }
  73904. if (position.z > 0) {
  73905. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73906. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73907. return true;
  73908. }
  73909. return true;
  73910. }
  73911. return false;
  73912. };
  73913. LensFlareSystem.prototype._isVisible = function () {
  73914. if (!this._isEnabled || !this._scene.activeCamera) {
  73915. return false;
  73916. }
  73917. var emitterPosition = this.getEmitterPosition();
  73918. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73919. var distance = direction.length();
  73920. direction.normalize();
  73921. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73922. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73923. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73924. };
  73925. LensFlareSystem.prototype.render = function () {
  73926. if (!this._effect.isReady() || !this._scene.activeCamera)
  73927. return false;
  73928. var engine = this._scene.getEngine();
  73929. var viewport = this._scene.activeCamera.viewport;
  73930. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73931. // Position
  73932. if (!this.computeEffectivePosition(globalViewport)) {
  73933. return false;
  73934. }
  73935. // Visibility
  73936. if (!this._isVisible()) {
  73937. return false;
  73938. }
  73939. // Intensity
  73940. var awayX;
  73941. var awayY;
  73942. if (this._positionX < this.borderLimit + globalViewport.x) {
  73943. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73944. }
  73945. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73946. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73947. }
  73948. else {
  73949. awayX = 0;
  73950. }
  73951. if (this._positionY < this.borderLimit + globalViewport.y) {
  73952. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73953. }
  73954. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73955. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73956. }
  73957. else {
  73958. awayY = 0;
  73959. }
  73960. var away = (awayX > awayY) ? awayX : awayY;
  73961. away -= this.viewportBorder;
  73962. if (away > this.borderLimit) {
  73963. away = this.borderLimit;
  73964. }
  73965. var intensity = 1.0 - (away / this.borderLimit);
  73966. if (intensity < 0) {
  73967. return false;
  73968. }
  73969. if (intensity > 1.0) {
  73970. intensity = 1.0;
  73971. }
  73972. if (this.viewportBorder > 0) {
  73973. globalViewport.x += this.viewportBorder;
  73974. globalViewport.y += this.viewportBorder;
  73975. globalViewport.width -= this.viewportBorder * 2;
  73976. globalViewport.height -= this.viewportBorder * 2;
  73977. this._positionX -= this.viewportBorder;
  73978. this._positionY -= this.viewportBorder;
  73979. }
  73980. // Position
  73981. var centerX = globalViewport.x + globalViewport.width / 2;
  73982. var centerY = globalViewport.y + globalViewport.height / 2;
  73983. var distX = centerX - this._positionX;
  73984. var distY = centerY - this._positionY;
  73985. // Effects
  73986. engine.enableEffect(this._effect);
  73987. engine.setState(false);
  73988. engine.setDepthBuffer(false);
  73989. // VBOs
  73990. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73991. // Flares
  73992. for (var index = 0; index < this.lensFlares.length; index++) {
  73993. var flare = this.lensFlares[index];
  73994. engine.setAlphaMode(flare.alphaMode);
  73995. var x = centerX - (distX * flare.position);
  73996. var y = centerY - (distY * flare.position);
  73997. var cw = flare.size;
  73998. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73999. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74000. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74001. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74002. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74003. // Texture
  74004. this._effect.setTexture("textureSampler", flare.texture);
  74005. // Color
  74006. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74007. // Draw order
  74008. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74009. }
  74010. engine.setDepthBuffer(true);
  74011. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74012. return true;
  74013. };
  74014. LensFlareSystem.prototype.dispose = function () {
  74015. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74016. if (vertexBuffer) {
  74017. vertexBuffer.dispose();
  74018. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74019. }
  74020. if (this._indexBuffer) {
  74021. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74022. this._indexBuffer = null;
  74023. }
  74024. while (this.lensFlares.length) {
  74025. this.lensFlares[0].dispose();
  74026. }
  74027. // Remove from scene
  74028. var index = this._scene.lensFlareSystems.indexOf(this);
  74029. this._scene.lensFlareSystems.splice(index, 1);
  74030. };
  74031. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74032. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74033. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74034. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74035. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74036. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74037. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74038. var parsedFlare = parsedLensFlareSystem.flares[index];
  74039. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74040. }
  74041. return lensFlareSystem;
  74042. };
  74043. LensFlareSystem.prototype.serialize = function () {
  74044. var serializationObject = {};
  74045. serializationObject.id = this.id;
  74046. serializationObject.name = this.name;
  74047. serializationObject.emitterId = this.getEmitter().id;
  74048. serializationObject.borderLimit = this.borderLimit;
  74049. serializationObject.flares = [];
  74050. for (var index = 0; index < this.lensFlares.length; index++) {
  74051. var flare = this.lensFlares[index];
  74052. serializationObject.flares.push({
  74053. size: flare.size,
  74054. position: flare.position,
  74055. color: flare.color.asArray(),
  74056. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74057. });
  74058. }
  74059. return serializationObject;
  74060. };
  74061. return LensFlareSystem;
  74062. }());
  74063. BABYLON.LensFlareSystem = LensFlareSystem;
  74064. })(BABYLON || (BABYLON = {}));
  74065. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74066. var BABYLON;
  74067. (function (BABYLON) {
  74068. /**
  74069. * This is a holder class for the physics joint created by the physics plugin.
  74070. * It holds a set of functions to control the underlying joint.
  74071. */
  74072. var PhysicsJoint = /** @class */ (function () {
  74073. function PhysicsJoint(type, jointData) {
  74074. this.type = type;
  74075. this.jointData = jointData;
  74076. jointData.nativeParams = jointData.nativeParams || {};
  74077. }
  74078. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74079. get: function () {
  74080. return this._physicsJoint;
  74081. },
  74082. set: function (newJoint) {
  74083. if (this._physicsJoint) {
  74084. //remove from the wolrd
  74085. }
  74086. this._physicsJoint = newJoint;
  74087. },
  74088. enumerable: true,
  74089. configurable: true
  74090. });
  74091. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74092. set: function (physicsPlugin) {
  74093. this._physicsPlugin = physicsPlugin;
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. /**
  74099. * Execute a function that is physics-plugin specific.
  74100. * @param {Function} func the function that will be executed.
  74101. * It accepts two parameters: the physics world and the physics joint.
  74102. */
  74103. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74104. func(this._physicsPlugin.world, this._physicsJoint);
  74105. };
  74106. //TODO check if the native joints are the same
  74107. //Joint Types
  74108. PhysicsJoint.DistanceJoint = 0;
  74109. PhysicsJoint.HingeJoint = 1;
  74110. PhysicsJoint.BallAndSocketJoint = 2;
  74111. PhysicsJoint.WheelJoint = 3;
  74112. PhysicsJoint.SliderJoint = 4;
  74113. //OIMO
  74114. PhysicsJoint.PrismaticJoint = 5;
  74115. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74116. PhysicsJoint.UniversalJoint = 6;
  74117. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74118. //Cannon
  74119. //Similar to a Ball-Joint. Different in params
  74120. PhysicsJoint.PointToPointJoint = 8;
  74121. //Cannon only at the moment
  74122. PhysicsJoint.SpringJoint = 9;
  74123. PhysicsJoint.LockJoint = 10;
  74124. return PhysicsJoint;
  74125. }());
  74126. BABYLON.PhysicsJoint = PhysicsJoint;
  74127. /**
  74128. * A class representing a physics distance joint.
  74129. */
  74130. var DistanceJoint = /** @class */ (function (_super) {
  74131. __extends(DistanceJoint, _super);
  74132. function DistanceJoint(jointData) {
  74133. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74134. }
  74135. /**
  74136. * Update the predefined distance.
  74137. */
  74138. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74139. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74140. };
  74141. return DistanceJoint;
  74142. }(PhysicsJoint));
  74143. BABYLON.DistanceJoint = DistanceJoint;
  74144. var MotorEnabledJoint = /** @class */ (function (_super) {
  74145. __extends(MotorEnabledJoint, _super);
  74146. function MotorEnabledJoint(type, jointData) {
  74147. return _super.call(this, type, jointData) || this;
  74148. }
  74149. /**
  74150. * Set the motor values.
  74151. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74152. * @param {number} force the force to apply
  74153. * @param {number} maxForce max force for this motor.
  74154. */
  74155. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74156. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74157. };
  74158. /**
  74159. * Set the motor's limits.
  74160. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74161. */
  74162. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74163. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74164. };
  74165. return MotorEnabledJoint;
  74166. }(PhysicsJoint));
  74167. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74168. /**
  74169. * This class represents a single hinge physics joint
  74170. */
  74171. var HingeJoint = /** @class */ (function (_super) {
  74172. __extends(HingeJoint, _super);
  74173. function HingeJoint(jointData) {
  74174. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74175. }
  74176. /**
  74177. * Set the motor values.
  74178. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74179. * @param {number} force the force to apply
  74180. * @param {number} maxForce max force for this motor.
  74181. */
  74182. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74183. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74184. };
  74185. /**
  74186. * Set the motor's limits.
  74187. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74188. */
  74189. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74190. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74191. };
  74192. return HingeJoint;
  74193. }(MotorEnabledJoint));
  74194. BABYLON.HingeJoint = HingeJoint;
  74195. /**
  74196. * This class represents a dual hinge physics joint (same as wheel joint)
  74197. */
  74198. var Hinge2Joint = /** @class */ (function (_super) {
  74199. __extends(Hinge2Joint, _super);
  74200. function Hinge2Joint(jointData) {
  74201. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74202. }
  74203. /**
  74204. * Set the motor values.
  74205. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74206. * @param {number} force the force to apply
  74207. * @param {number} maxForce max force for this motor.
  74208. * @param {motorIndex} the motor's index, 0 or 1.
  74209. */
  74210. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74211. if (motorIndex === void 0) { motorIndex = 0; }
  74212. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74213. };
  74214. /**
  74215. * Set the motor limits.
  74216. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74217. * @param {number} upperLimit the upper limit
  74218. * @param {number} lowerLimit lower limit
  74219. * @param {motorIndex} the motor's index, 0 or 1.
  74220. */
  74221. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74222. if (motorIndex === void 0) { motorIndex = 0; }
  74223. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74224. };
  74225. return Hinge2Joint;
  74226. }(MotorEnabledJoint));
  74227. BABYLON.Hinge2Joint = Hinge2Joint;
  74228. })(BABYLON || (BABYLON = {}));
  74229. //# sourceMappingURL=babylon.physicsJoint.js.map
  74230. var BABYLON;
  74231. (function (BABYLON) {
  74232. var PhysicsImpostor = /** @class */ (function () {
  74233. function PhysicsImpostor(object, type, _options, _scene) {
  74234. if (_options === void 0) { _options = { mass: 0 }; }
  74235. var _this = this;
  74236. this.object = object;
  74237. this.type = type;
  74238. this._options = _options;
  74239. this._scene = _scene;
  74240. this._bodyUpdateRequired = false;
  74241. this._onBeforePhysicsStepCallbacks = new Array();
  74242. this._onAfterPhysicsStepCallbacks = new Array();
  74243. this._onPhysicsCollideCallbacks = [];
  74244. this._deltaPosition = BABYLON.Vector3.Zero();
  74245. this._isDisposed = false;
  74246. //temp variables for parent rotation calculations
  74247. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74248. this._tmpQuat = new BABYLON.Quaternion();
  74249. this._tmpQuat2 = new BABYLON.Quaternion();
  74250. /**
  74251. * this function is executed by the physics engine.
  74252. */
  74253. this.beforeStep = function () {
  74254. if (!_this._physicsEngine) {
  74255. return;
  74256. }
  74257. _this.object.translate(_this._deltaPosition, -1);
  74258. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74259. _this.object.computeWorldMatrix(false);
  74260. if (_this.object.parent && _this.object.rotationQuaternion) {
  74261. _this.getParentsRotation();
  74262. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74263. }
  74264. else {
  74265. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74266. }
  74267. if (!_this._options.disableBidirectionalTransformation) {
  74268. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74269. }
  74270. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74271. func(_this);
  74272. });
  74273. };
  74274. /**
  74275. * this function is executed by the physics engine.
  74276. */
  74277. this.afterStep = function () {
  74278. if (!_this._physicsEngine) {
  74279. return;
  74280. }
  74281. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74282. func(_this);
  74283. });
  74284. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74285. // object has now its world rotation. needs to be converted to local.
  74286. if (_this.object.parent && _this.object.rotationQuaternion) {
  74287. _this.getParentsRotation();
  74288. _this._tmpQuat.conjugateInPlace();
  74289. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74290. }
  74291. // take the position set and make it the absolute position of this object.
  74292. _this.object.setAbsolutePosition(_this.object.position);
  74293. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74294. _this.object.translate(_this._deltaPosition, 1);
  74295. };
  74296. /**
  74297. * Legacy collision detection event support
  74298. */
  74299. this.onCollideEvent = null;
  74300. //event and body object due to cannon's event-based architecture.
  74301. this.onCollide = function (e) {
  74302. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74303. return;
  74304. }
  74305. if (!_this._physicsEngine) {
  74306. return;
  74307. }
  74308. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74309. if (otherImpostor) {
  74310. // Legacy collision detection event support
  74311. if (_this.onCollideEvent) {
  74312. _this.onCollideEvent(_this, otherImpostor);
  74313. }
  74314. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74315. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74316. }).forEach(function (obj) {
  74317. obj.callback(_this, otherImpostor);
  74318. });
  74319. }
  74320. };
  74321. //sanity check!
  74322. if (!this.object) {
  74323. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74324. return;
  74325. }
  74326. //legacy support for old syntax.
  74327. if (!this._scene && object.getScene) {
  74328. this._scene = object.getScene();
  74329. }
  74330. if (!this._scene) {
  74331. return;
  74332. }
  74333. this._physicsEngine = this._scene.getPhysicsEngine();
  74334. if (!this._physicsEngine) {
  74335. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74336. }
  74337. else {
  74338. //set the object's quaternion, if not set
  74339. if (!this.object.rotationQuaternion) {
  74340. if (this.object.rotation) {
  74341. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74342. }
  74343. else {
  74344. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74345. }
  74346. }
  74347. //default options params
  74348. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74349. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74350. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74351. this._joints = [];
  74352. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74353. if (!this.object.parent || this._options.ignoreParent) {
  74354. this._init();
  74355. }
  74356. else if (this.object.parent.physicsImpostor) {
  74357. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74358. }
  74359. }
  74360. }
  74361. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74362. get: function () {
  74363. return this._isDisposed;
  74364. },
  74365. enumerable: true,
  74366. configurable: true
  74367. });
  74368. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74369. get: function () {
  74370. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74371. },
  74372. set: function (value) {
  74373. this.setMass(value);
  74374. },
  74375. enumerable: true,
  74376. configurable: true
  74377. });
  74378. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74379. get: function () {
  74380. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74381. },
  74382. set: function (value) {
  74383. if (!this._physicsEngine) {
  74384. return;
  74385. }
  74386. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74387. },
  74388. enumerable: true,
  74389. configurable: true
  74390. });
  74391. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74392. get: function () {
  74393. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74394. },
  74395. set: function (value) {
  74396. if (!this._physicsEngine) {
  74397. return;
  74398. }
  74399. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74400. },
  74401. enumerable: true,
  74402. configurable: true
  74403. });
  74404. /**
  74405. * This function will completly initialize this impostor.
  74406. * It will create a new body - but only if this mesh has no parent.
  74407. * If it has, this impostor will not be used other than to define the impostor
  74408. * of the child mesh.
  74409. */
  74410. PhysicsImpostor.prototype._init = function () {
  74411. if (!this._physicsEngine) {
  74412. return;
  74413. }
  74414. this._physicsEngine.removeImpostor(this);
  74415. this.physicsBody = null;
  74416. this._parent = this._parent || this._getPhysicsParent();
  74417. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74418. this._physicsEngine.addImpostor(this);
  74419. }
  74420. };
  74421. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74422. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74423. var parentMesh = this.object.parent;
  74424. return parentMesh.physicsImpostor;
  74425. }
  74426. return null;
  74427. };
  74428. /**
  74429. * Should a new body be generated.
  74430. */
  74431. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74432. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74433. };
  74434. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74435. this.forceUpdate();
  74436. };
  74437. /**
  74438. * Force a regeneration of this or the parent's impostor's body.
  74439. * Use under cautious - This will remove all joints already implemented.
  74440. */
  74441. PhysicsImpostor.prototype.forceUpdate = function () {
  74442. this._init();
  74443. if (this.parent && !this._options.ignoreParent) {
  74444. this.parent.forceUpdate();
  74445. }
  74446. };
  74447. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74448. /*public get mesh(): AbstractMesh {
  74449. return this._mesh;
  74450. }*/
  74451. /**
  74452. * Gets the body that holds this impostor. Either its own, or its parent.
  74453. */
  74454. get: function () {
  74455. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74456. },
  74457. /**
  74458. * Set the physics body. Used mainly by the physics engine/plugin
  74459. */
  74460. set: function (physicsBody) {
  74461. if (this._physicsBody && this._physicsEngine) {
  74462. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74463. }
  74464. this._physicsBody = physicsBody;
  74465. this.resetUpdateFlags();
  74466. },
  74467. enumerable: true,
  74468. configurable: true
  74469. });
  74470. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74471. get: function () {
  74472. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74473. },
  74474. set: function (value) {
  74475. this._parent = value;
  74476. },
  74477. enumerable: true,
  74478. configurable: true
  74479. });
  74480. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74481. this._bodyUpdateRequired = false;
  74482. };
  74483. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74484. if (this.object.getBoundingInfo) {
  74485. var q = this.object.rotationQuaternion;
  74486. //reset rotation
  74487. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74488. //calculate the world matrix with no rotation
  74489. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74490. var boundingInfo = this.object.getBoundingInfo();
  74491. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74492. //bring back the rotation
  74493. this.object.rotationQuaternion = q;
  74494. //calculate the world matrix with the new rotation
  74495. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74496. return size;
  74497. }
  74498. else {
  74499. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74500. }
  74501. };
  74502. PhysicsImpostor.prototype.getObjectCenter = function () {
  74503. if (this.object.getBoundingInfo) {
  74504. var boundingInfo = this.object.getBoundingInfo();
  74505. return boundingInfo.boundingBox.centerWorld;
  74506. }
  74507. else {
  74508. return this.object.position;
  74509. }
  74510. };
  74511. /**
  74512. * Get a specific parametes from the options parameter.
  74513. */
  74514. PhysicsImpostor.prototype.getParam = function (paramName) {
  74515. return this._options[paramName];
  74516. };
  74517. /**
  74518. * Sets a specific parameter in the options given to the physics plugin
  74519. */
  74520. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74521. this._options[paramName] = value;
  74522. this._bodyUpdateRequired = true;
  74523. };
  74524. /**
  74525. * Specifically change the body's mass option. Won't recreate the physics body object
  74526. */
  74527. PhysicsImpostor.prototype.setMass = function (mass) {
  74528. if (this.getParam("mass") !== mass) {
  74529. this.setParam("mass", mass);
  74530. }
  74531. if (this._physicsEngine) {
  74532. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74533. }
  74534. };
  74535. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74536. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74537. };
  74538. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74539. if (this._physicsEngine) {
  74540. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74541. }
  74542. };
  74543. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74544. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74545. };
  74546. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74547. if (this._physicsEngine) {
  74548. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74549. }
  74550. };
  74551. /**
  74552. * Execute a function with the physics plugin native code.
  74553. * Provide a function the will have two variables - the world object and the physics body object.
  74554. */
  74555. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74556. if (this._physicsEngine) {
  74557. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74558. }
  74559. };
  74560. /**
  74561. * Register a function that will be executed before the physics world is stepping forward.
  74562. */
  74563. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74564. this._onBeforePhysicsStepCallbacks.push(func);
  74565. };
  74566. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74567. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74568. if (index > -1) {
  74569. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74570. }
  74571. else {
  74572. BABYLON.Tools.Warn("Function to remove was not found");
  74573. }
  74574. };
  74575. /**
  74576. * Register a function that will be executed after the physics step
  74577. */
  74578. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74579. this._onAfterPhysicsStepCallbacks.push(func);
  74580. };
  74581. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74582. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74583. if (index > -1) {
  74584. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74585. }
  74586. else {
  74587. BABYLON.Tools.Warn("Function to remove was not found");
  74588. }
  74589. };
  74590. /**
  74591. * register a function that will be executed when this impostor collides against a different body.
  74592. */
  74593. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74594. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74595. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74596. };
  74597. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74598. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74599. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74600. if (index > -1) {
  74601. this._onPhysicsCollideCallbacks.splice(index, 1);
  74602. }
  74603. else {
  74604. BABYLON.Tools.Warn("Function to remove was not found");
  74605. }
  74606. };
  74607. PhysicsImpostor.prototype.getParentsRotation = function () {
  74608. var parent = this.object.parent;
  74609. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74610. while (parent) {
  74611. if (parent.rotationQuaternion) {
  74612. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74613. }
  74614. else {
  74615. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74616. }
  74617. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74618. parent = parent.parent;
  74619. }
  74620. return this._tmpQuat;
  74621. };
  74622. /**
  74623. * Apply a force
  74624. */
  74625. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74626. if (this._physicsEngine) {
  74627. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74628. }
  74629. return this;
  74630. };
  74631. /**
  74632. * Apply an impulse
  74633. */
  74634. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74635. if (this._physicsEngine) {
  74636. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74637. }
  74638. return this;
  74639. };
  74640. /**
  74641. * A help function to create a joint.
  74642. */
  74643. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74644. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74645. this.addJoint(otherImpostor, joint);
  74646. return this;
  74647. };
  74648. /**
  74649. * Add a joint to this impostor with a different impostor.
  74650. */
  74651. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74652. this._joints.push({
  74653. otherImpostor: otherImpostor,
  74654. joint: joint
  74655. });
  74656. if (this._physicsEngine) {
  74657. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74658. }
  74659. return this;
  74660. };
  74661. /**
  74662. * Will keep this body still, in a sleep mode.
  74663. */
  74664. PhysicsImpostor.prototype.sleep = function () {
  74665. if (this._physicsEngine) {
  74666. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74667. }
  74668. return this;
  74669. };
  74670. /**
  74671. * Wake the body up.
  74672. */
  74673. PhysicsImpostor.prototype.wakeUp = function () {
  74674. if (this._physicsEngine) {
  74675. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74676. }
  74677. return this;
  74678. };
  74679. PhysicsImpostor.prototype.clone = function (newObject) {
  74680. if (!newObject)
  74681. return null;
  74682. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74683. };
  74684. PhysicsImpostor.prototype.dispose = function () {
  74685. var _this = this;
  74686. //no dispose if no physics engine is available.
  74687. if (!this._physicsEngine) {
  74688. return;
  74689. }
  74690. this._joints.forEach(function (j) {
  74691. if (_this._physicsEngine) {
  74692. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  74693. }
  74694. });
  74695. //dispose the physics body
  74696. this._physicsEngine.removeImpostor(this);
  74697. if (this.parent) {
  74698. this.parent.forceUpdate();
  74699. }
  74700. else {
  74701. /*this._object.getChildMeshes().forEach(function(mesh) {
  74702. if (mesh.physicsImpostor) {
  74703. if (disposeChildren) {
  74704. mesh.physicsImpostor.dispose();
  74705. mesh.physicsImpostor = null;
  74706. }
  74707. }
  74708. })*/
  74709. }
  74710. this._isDisposed = true;
  74711. };
  74712. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  74713. this._deltaPosition.copyFrom(position);
  74714. };
  74715. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  74716. if (!this._deltaRotation) {
  74717. this._deltaRotation = new BABYLON.Quaternion();
  74718. }
  74719. this._deltaRotation.copyFrom(rotation);
  74720. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  74721. };
  74722. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  74723. if (this._physicsEngine) {
  74724. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  74725. }
  74726. return this;
  74727. };
  74728. PhysicsImpostor.prototype.getRadius = function () {
  74729. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  74730. };
  74731. /**
  74732. * Sync a bone with this impostor
  74733. * @param bone The bone to sync to the impostor.
  74734. * @param boneMesh The mesh that the bone is influencing.
  74735. * @param jointPivot The pivot of the joint / bone in local space.
  74736. * @param distToJoint Optional distance from the impostor to the joint.
  74737. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74738. */
  74739. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  74740. var tempVec = PhysicsImpostor._tmpVecs[0];
  74741. var mesh = this.object;
  74742. if (mesh.rotationQuaternion) {
  74743. if (adjustRotation) {
  74744. var tempQuat = PhysicsImpostor._tmpQuat;
  74745. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  74746. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  74747. }
  74748. else {
  74749. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  74750. }
  74751. }
  74752. tempVec.x = 0;
  74753. tempVec.y = 0;
  74754. tempVec.z = 0;
  74755. if (jointPivot) {
  74756. tempVec.x = jointPivot.x;
  74757. tempVec.y = jointPivot.y;
  74758. tempVec.z = jointPivot.z;
  74759. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  74760. if (distToJoint === undefined || distToJoint === null) {
  74761. distToJoint = jointPivot.length();
  74762. }
  74763. tempVec.x *= distToJoint;
  74764. tempVec.y *= distToJoint;
  74765. tempVec.z *= distToJoint;
  74766. }
  74767. if (bone.getParent()) {
  74768. tempVec.addInPlace(mesh.getAbsolutePosition());
  74769. bone.setAbsolutePosition(tempVec, boneMesh);
  74770. }
  74771. else {
  74772. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  74773. boneMesh.position.x -= tempVec.x;
  74774. boneMesh.position.y -= tempVec.y;
  74775. boneMesh.position.z -= tempVec.z;
  74776. }
  74777. };
  74778. /**
  74779. * Sync impostor to a bone
  74780. * @param bone The bone that the impostor will be synced to.
  74781. * @param boneMesh The mesh that the bone is influencing.
  74782. * @param jointPivot The pivot of the joint / bone in local space.
  74783. * @param distToJoint Optional distance from the impostor to the joint.
  74784. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74785. * @param boneAxis Optional vector3 axis the bone is aligned with
  74786. */
  74787. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  74788. var mesh = this.object;
  74789. if (mesh.rotationQuaternion) {
  74790. if (adjustRotation) {
  74791. var tempQuat = PhysicsImpostor._tmpQuat;
  74792. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  74793. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  74794. }
  74795. else {
  74796. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  74797. }
  74798. }
  74799. var pos = PhysicsImpostor._tmpVecs[0];
  74800. var boneDir = PhysicsImpostor._tmpVecs[1];
  74801. if (!boneAxis) {
  74802. boneAxis = PhysicsImpostor._tmpVecs[2];
  74803. boneAxis.x = 0;
  74804. boneAxis.y = 1;
  74805. boneAxis.z = 0;
  74806. }
  74807. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  74808. bone.getAbsolutePositionToRef(boneMesh, pos);
  74809. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  74810. distToJoint = jointPivot.length();
  74811. }
  74812. if (distToJoint !== undefined && distToJoint !== null) {
  74813. pos.x += boneDir.x * distToJoint;
  74814. pos.y += boneDir.y * distToJoint;
  74815. pos.z += boneDir.z * distToJoint;
  74816. }
  74817. mesh.setAbsolutePosition(pos);
  74818. };
  74819. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  74820. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  74821. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74822. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  74823. //Impostor types
  74824. PhysicsImpostor.NoImpostor = 0;
  74825. PhysicsImpostor.SphereImpostor = 1;
  74826. PhysicsImpostor.BoxImpostor = 2;
  74827. PhysicsImpostor.PlaneImpostor = 3;
  74828. PhysicsImpostor.MeshImpostor = 4;
  74829. PhysicsImpostor.CylinderImpostor = 7;
  74830. PhysicsImpostor.ParticleImpostor = 8;
  74831. PhysicsImpostor.HeightmapImpostor = 9;
  74832. return PhysicsImpostor;
  74833. }());
  74834. BABYLON.PhysicsImpostor = PhysicsImpostor;
  74835. })(BABYLON || (BABYLON = {}));
  74836. //# sourceMappingURL=babylon.physicsImpostor.js.map
  74837. var BABYLON;
  74838. (function (BABYLON) {
  74839. var PhysicsEngine = /** @class */ (function () {
  74840. function PhysicsEngine(gravity, _physicsPlugin) {
  74841. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  74842. this._physicsPlugin = _physicsPlugin;
  74843. //new methods and parameters
  74844. this._impostors = [];
  74845. this._joints = [];
  74846. if (!this._physicsPlugin.isSupported()) {
  74847. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74848. + "Please make sure it is included.");
  74849. }
  74850. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74851. this.setGravity(gravity);
  74852. this.setTimeStep();
  74853. }
  74854. PhysicsEngine.prototype.setGravity = function (gravity) {
  74855. this.gravity = gravity;
  74856. this._physicsPlugin.setGravity(this.gravity);
  74857. };
  74858. /**
  74859. * Set the time step of the physics engine.
  74860. * default is 1/60.
  74861. * To slow it down, enter 1/600 for example.
  74862. * To speed it up, 1/30
  74863. * @param {number} newTimeStep the new timestep to apply to this world.
  74864. */
  74865. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74866. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74867. this._physicsPlugin.setTimeStep(newTimeStep);
  74868. };
  74869. /**
  74870. * Get the time step of the physics engine.
  74871. */
  74872. PhysicsEngine.prototype.getTimeStep = function () {
  74873. return this._physicsPlugin.getTimeStep();
  74874. };
  74875. PhysicsEngine.prototype.dispose = function () {
  74876. this._impostors.forEach(function (impostor) {
  74877. impostor.dispose();
  74878. });
  74879. this._physicsPlugin.dispose();
  74880. };
  74881. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74882. return this._physicsPlugin.name;
  74883. };
  74884. /**
  74885. * Adding a new impostor for the impostor tracking.
  74886. * This will be done by the impostor itself.
  74887. * @param {PhysicsImpostor} impostor the impostor to add
  74888. */
  74889. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74890. impostor.uniqueId = this._impostors.push(impostor);
  74891. //if no parent, generate the body
  74892. if (!impostor.parent) {
  74893. this._physicsPlugin.generatePhysicsBody(impostor);
  74894. }
  74895. };
  74896. /**
  74897. * Remove an impostor from the engine.
  74898. * This impostor and its mesh will not longer be updated by the physics engine.
  74899. * @param {PhysicsImpostor} impostor the impostor to remove
  74900. */
  74901. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74902. var index = this._impostors.indexOf(impostor);
  74903. if (index > -1) {
  74904. var removed = this._impostors.splice(index, 1);
  74905. //Is it needed?
  74906. if (removed.length) {
  74907. //this will also remove it from the world.
  74908. removed[0].physicsBody = null;
  74909. }
  74910. }
  74911. };
  74912. /**
  74913. * Add a joint to the physics engine
  74914. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74915. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74916. * @param {PhysicsJoint} the joint that will connect both impostors.
  74917. */
  74918. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74919. var impostorJoint = {
  74920. mainImpostor: mainImpostor,
  74921. connectedImpostor: connectedImpostor,
  74922. joint: joint
  74923. };
  74924. joint.physicsPlugin = this._physicsPlugin;
  74925. this._joints.push(impostorJoint);
  74926. this._physicsPlugin.generateJoint(impostorJoint);
  74927. };
  74928. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74929. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74930. return (impostorJoint.connectedImpostor === connectedImpostor
  74931. && impostorJoint.joint === joint
  74932. && impostorJoint.mainImpostor === mainImpostor);
  74933. });
  74934. if (matchingJoints.length) {
  74935. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74936. //TODO remove it from the list as well
  74937. }
  74938. };
  74939. /**
  74940. * Called by the scene. no need to call it.
  74941. */
  74942. PhysicsEngine.prototype._step = function (delta) {
  74943. var _this = this;
  74944. //check if any mesh has no body / requires an update
  74945. this._impostors.forEach(function (impostor) {
  74946. if (impostor.isBodyInitRequired()) {
  74947. _this._physicsPlugin.generatePhysicsBody(impostor);
  74948. }
  74949. });
  74950. if (delta > 0.1) {
  74951. delta = 0.1;
  74952. }
  74953. else if (delta <= 0) {
  74954. delta = 1.0 / 60.0;
  74955. }
  74956. this._physicsPlugin.executeStep(delta, this._impostors);
  74957. };
  74958. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74959. return this._physicsPlugin;
  74960. };
  74961. PhysicsEngine.prototype.getImpostors = function () {
  74962. return this._impostors;
  74963. };
  74964. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74965. for (var i = 0; i < this._impostors.length; ++i) {
  74966. if (this._impostors[i].object === object) {
  74967. return this._impostors[i];
  74968. }
  74969. }
  74970. return null;
  74971. };
  74972. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74973. for (var i = 0; i < this._impostors.length; ++i) {
  74974. if (this._impostors[i].physicsBody === body) {
  74975. return this._impostors[i];
  74976. }
  74977. }
  74978. return null;
  74979. };
  74980. // Statics
  74981. PhysicsEngine.Epsilon = 0.001;
  74982. return PhysicsEngine;
  74983. }());
  74984. BABYLON.PhysicsEngine = PhysicsEngine;
  74985. })(BABYLON || (BABYLON = {}));
  74986. //# sourceMappingURL=babylon.physicsEngine.js.map
  74987. var BABYLON;
  74988. (function (BABYLON) {
  74989. var PhysicsHelper = /** @class */ (function () {
  74990. function PhysicsHelper(scene) {
  74991. this._scene = scene;
  74992. this._physicsEngine = this._scene.getPhysicsEngine();
  74993. if (!this._physicsEngine) {
  74994. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74995. }
  74996. }
  74997. /**
  74998. * @param {Vector3} origin the origin of the explosion
  74999. * @param {number} radius the explosion radius
  75000. * @param {number} strength the explosion strength
  75001. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75002. */
  75003. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75004. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75005. if (!this._physicsEngine) {
  75006. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75007. return null;
  75008. }
  75009. var impostors = this._physicsEngine.getImpostors();
  75010. if (impostors.length === 0) {
  75011. return null;
  75012. }
  75013. var event = new PhysicsRadialExplosionEvent(this._scene);
  75014. impostors.forEach(function (impostor) {
  75015. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75016. if (!impostorForceAndContactPoint) {
  75017. return;
  75018. }
  75019. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75020. });
  75021. event.dispose(false);
  75022. return event;
  75023. };
  75024. /**
  75025. * @param {Vector3} origin the origin of the explosion
  75026. * @param {number} radius the explosion radius
  75027. * @param {number} strength the explosion strength
  75028. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75029. */
  75030. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75031. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75032. if (!this._physicsEngine) {
  75033. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75034. return null;
  75035. }
  75036. var impostors = this._physicsEngine.getImpostors();
  75037. if (impostors.length === 0) {
  75038. return null;
  75039. }
  75040. var event = new PhysicsRadialExplosionEvent(this._scene);
  75041. impostors.forEach(function (impostor) {
  75042. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75043. if (!impostorForceAndContactPoint) {
  75044. return;
  75045. }
  75046. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75047. });
  75048. event.dispose(false);
  75049. return event;
  75050. };
  75051. /**
  75052. * @param {Vector3} origin the origin of the explosion
  75053. * @param {number} radius the explosion radius
  75054. * @param {number} strength the explosion strength
  75055. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75056. */
  75057. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75058. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75059. if (!this._physicsEngine) {
  75060. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75061. return null;
  75062. }
  75063. var impostors = this._physicsEngine.getImpostors();
  75064. if (impostors.length === 0) {
  75065. return null;
  75066. }
  75067. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75068. event.dispose(false);
  75069. return event;
  75070. };
  75071. /**
  75072. * @param {Vector3} origin the origin of the updraft
  75073. * @param {number} radius the radius of the updraft
  75074. * @param {number} strength the strength of the updraft
  75075. * @param {number} height the height of the updraft
  75076. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75077. */
  75078. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75079. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75080. if (!this._physicsEngine) {
  75081. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75082. return null;
  75083. }
  75084. if (this._physicsEngine.getImpostors().length === 0) {
  75085. return null;
  75086. }
  75087. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75088. event.dispose(false);
  75089. return event;
  75090. };
  75091. /**
  75092. * @param {Vector3} origin the of the vortex
  75093. * @param {number} radius the radius of the vortex
  75094. * @param {number} strength the strength of the vortex
  75095. * @param {number} height the height of the vortex
  75096. */
  75097. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75098. if (!this._physicsEngine) {
  75099. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75100. return null;
  75101. }
  75102. if (this._physicsEngine.getImpostors().length === 0) {
  75103. return null;
  75104. }
  75105. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75106. event.dispose(false);
  75107. return event;
  75108. };
  75109. return PhysicsHelper;
  75110. }());
  75111. BABYLON.PhysicsHelper = PhysicsHelper;
  75112. /***** Radial explosion *****/
  75113. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75114. function PhysicsRadialExplosionEvent(scene) {
  75115. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75116. this._rays = [];
  75117. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75118. this._scene = scene;
  75119. }
  75120. /**
  75121. * Returns the data related to the radial explosion event (sphere & rays).
  75122. * @returns {PhysicsRadialExplosionEventData}
  75123. */
  75124. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75125. this._dataFetched = true;
  75126. return {
  75127. sphere: this._sphere,
  75128. rays: this._rays,
  75129. };
  75130. };
  75131. /**
  75132. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75133. * @param impostor
  75134. * @param {Vector3} origin the origin of the explosion
  75135. * @param {number} radius the explosion radius
  75136. * @param {number} strength the explosion strength
  75137. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75138. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75139. */
  75140. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75141. if (impostor.mass === 0) {
  75142. return null;
  75143. }
  75144. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75145. return null;
  75146. }
  75147. if (impostor.object.getClassName() !== 'Mesh') {
  75148. return null;
  75149. }
  75150. var impostorObject = impostor.object;
  75151. var impostorObjectCenter = impostor.getObjectCenter();
  75152. var direction = impostorObjectCenter.subtract(origin);
  75153. var ray = new BABYLON.Ray(origin, direction, radius);
  75154. this._rays.push(ray);
  75155. var hit = ray.intersectsMesh(impostorObject);
  75156. var contactPoint = hit.pickedPoint;
  75157. if (!contactPoint) {
  75158. return null;
  75159. }
  75160. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75161. if (distanceFromOrigin > radius) {
  75162. return null;
  75163. }
  75164. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75165. ? strength
  75166. : strength * (1 - (distanceFromOrigin / radius));
  75167. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75168. return { force: force, contactPoint: contactPoint };
  75169. };
  75170. /**
  75171. * Disposes the sphere.
  75172. * @param {bolean} force
  75173. */
  75174. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75175. var _this = this;
  75176. if (force === void 0) { force = true; }
  75177. if (force) {
  75178. this._sphere.dispose();
  75179. }
  75180. else {
  75181. setTimeout(function () {
  75182. if (!_this._dataFetched) {
  75183. _this._sphere.dispose();
  75184. }
  75185. }, 0);
  75186. }
  75187. };
  75188. /*** Helpers ***/
  75189. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75190. if (!this._sphere) {
  75191. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75192. this._sphere.isVisible = false;
  75193. }
  75194. };
  75195. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75196. var impostorObject = impostor.object;
  75197. this._prepareSphere();
  75198. this._sphere.position = origin;
  75199. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75200. this._sphere._updateBoundingInfo();
  75201. this._sphere.computeWorldMatrix(true);
  75202. return this._sphere.intersectsMesh(impostorObject, true);
  75203. };
  75204. return PhysicsRadialExplosionEvent;
  75205. }());
  75206. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75207. /***** Gravitational Field *****/
  75208. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75209. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75210. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75211. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75212. this._physicsHelper = physicsHelper;
  75213. this._scene = scene;
  75214. this._origin = origin;
  75215. this._radius = radius;
  75216. this._strength = strength;
  75217. this._falloff = falloff;
  75218. this._tickCallback = this._tick.bind(this);
  75219. }
  75220. /**
  75221. * Returns the data related to the gravitational field event (sphere).
  75222. * @returns {PhysicsGravitationalFieldEventData}
  75223. */
  75224. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75225. this._dataFetched = true;
  75226. return {
  75227. sphere: this._sphere,
  75228. };
  75229. };
  75230. /**
  75231. * Enables the gravitational field.
  75232. */
  75233. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75234. this._tickCallback.call(this);
  75235. this._scene.registerBeforeRender(this._tickCallback);
  75236. };
  75237. /**
  75238. * Disables the gravitational field.
  75239. */
  75240. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75241. this._scene.unregisterBeforeRender(this._tickCallback);
  75242. };
  75243. /**
  75244. * Disposes the sphere.
  75245. * @param {bolean} force
  75246. */
  75247. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75248. var _this = this;
  75249. if (force === void 0) { force = true; }
  75250. if (force) {
  75251. this._sphere.dispose();
  75252. }
  75253. else {
  75254. setTimeout(function () {
  75255. if (!_this._dataFetched) {
  75256. _this._sphere.dispose();
  75257. }
  75258. }, 0);
  75259. }
  75260. };
  75261. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75262. // Since the params won't change, we fetch the event only once
  75263. if (this._sphere) {
  75264. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75265. }
  75266. else {
  75267. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75268. if (radialExplosionEvent) {
  75269. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75270. }
  75271. }
  75272. };
  75273. return PhysicsGravitationalFieldEvent;
  75274. }());
  75275. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75276. /***** Updraft *****/
  75277. var PhysicsUpdraftEvent = /** @class */ (function () {
  75278. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75279. this._scene = _scene;
  75280. this._origin = _origin;
  75281. this._radius = _radius;
  75282. this._strength = _strength;
  75283. this._height = _height;
  75284. this._updraftMode = _updraftMode;
  75285. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75286. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75287. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75288. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75289. this._physicsEngine = this._scene.getPhysicsEngine();
  75290. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75291. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75292. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75293. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75294. }
  75295. this._tickCallback = this._tick.bind(this);
  75296. }
  75297. /**
  75298. * Returns the data related to the updraft event (cylinder).
  75299. * @returns {PhysicsUpdraftEventData}
  75300. */
  75301. PhysicsUpdraftEvent.prototype.getData = function () {
  75302. this._dataFetched = true;
  75303. return {
  75304. cylinder: this._cylinder,
  75305. };
  75306. };
  75307. /**
  75308. * Enables the updraft.
  75309. */
  75310. PhysicsUpdraftEvent.prototype.enable = function () {
  75311. this._tickCallback.call(this);
  75312. this._scene.registerBeforeRender(this._tickCallback);
  75313. };
  75314. /**
  75315. * Disables the cortex.
  75316. */
  75317. PhysicsUpdraftEvent.prototype.disable = function () {
  75318. this._scene.unregisterBeforeRender(this._tickCallback);
  75319. };
  75320. /**
  75321. * Disposes the sphere.
  75322. * @param {bolean} force
  75323. */
  75324. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75325. var _this = this;
  75326. if (force === void 0) { force = true; }
  75327. if (force) {
  75328. this._cylinder.dispose();
  75329. }
  75330. else {
  75331. setTimeout(function () {
  75332. if (!_this._dataFetched) {
  75333. _this._cylinder.dispose();
  75334. }
  75335. }, 0);
  75336. }
  75337. };
  75338. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75339. if (impostor.mass === 0) {
  75340. return null;
  75341. }
  75342. if (!this._intersectsWithCylinder(impostor)) {
  75343. return null;
  75344. }
  75345. var impostorObjectCenter = impostor.getObjectCenter();
  75346. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75347. var direction = this._originDirection;
  75348. }
  75349. else {
  75350. var direction = impostorObjectCenter.subtract(this._originTop);
  75351. }
  75352. var multiplier = this._strength * -1;
  75353. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75354. return { force: force, contactPoint: impostorObjectCenter };
  75355. };
  75356. PhysicsUpdraftEvent.prototype._tick = function () {
  75357. var _this = this;
  75358. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75359. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75360. if (!impostorForceAndContactPoint) {
  75361. return;
  75362. }
  75363. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75364. });
  75365. };
  75366. /*** Helpers ***/
  75367. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75368. if (!this._cylinder) {
  75369. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75370. height: this._height,
  75371. diameter: this._radius * 2,
  75372. }, this._scene);
  75373. this._cylinder.isVisible = false;
  75374. }
  75375. };
  75376. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75377. var impostorObject = impostor.object;
  75378. this._prepareCylinder();
  75379. this._cylinder.position = this._cylinderPosition;
  75380. return this._cylinder.intersectsMesh(impostorObject, true);
  75381. };
  75382. return PhysicsUpdraftEvent;
  75383. }());
  75384. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75385. /***** Vortex *****/
  75386. var PhysicsVortexEvent = /** @class */ (function () {
  75387. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75388. this._scene = _scene;
  75389. this._origin = _origin;
  75390. this._radius = _radius;
  75391. this._strength = _strength;
  75392. this._height = _height;
  75393. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75394. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75395. this._updraftMultiplier = 0.02;
  75396. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75397. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75398. this._physicsEngine = this._scene.getPhysicsEngine();
  75399. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75400. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75401. this._tickCallback = this._tick.bind(this);
  75402. }
  75403. /**
  75404. * Returns the data related to the vortex event (cylinder).
  75405. * @returns {PhysicsVortexEventData}
  75406. */
  75407. PhysicsVortexEvent.prototype.getData = function () {
  75408. this._dataFetched = true;
  75409. return {
  75410. cylinder: this._cylinder,
  75411. };
  75412. };
  75413. /**
  75414. * Enables the vortex.
  75415. */
  75416. PhysicsVortexEvent.prototype.enable = function () {
  75417. this._tickCallback.call(this);
  75418. this._scene.registerBeforeRender(this._tickCallback);
  75419. };
  75420. /**
  75421. * Disables the cortex.
  75422. */
  75423. PhysicsVortexEvent.prototype.disable = function () {
  75424. this._scene.unregisterBeforeRender(this._tickCallback);
  75425. };
  75426. /**
  75427. * Disposes the sphere.
  75428. * @param {bolean} force
  75429. */
  75430. PhysicsVortexEvent.prototype.dispose = function (force) {
  75431. var _this = this;
  75432. if (force === void 0) { force = true; }
  75433. if (force) {
  75434. this._cylinder.dispose();
  75435. }
  75436. else {
  75437. setTimeout(function () {
  75438. if (!_this._dataFetched) {
  75439. _this._cylinder.dispose();
  75440. }
  75441. }, 0);
  75442. }
  75443. };
  75444. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75445. if (impostor.mass === 0) {
  75446. return null;
  75447. }
  75448. if (!this._intersectsWithCylinder(impostor)) {
  75449. return null;
  75450. }
  75451. if (impostor.object.getClassName() !== 'Mesh') {
  75452. return null;
  75453. }
  75454. var impostorObject = impostor.object;
  75455. var impostorObjectCenter = impostor.getObjectCenter();
  75456. 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)
  75457. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75458. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75459. var hit = ray.intersectsMesh(impostorObject);
  75460. var contactPoint = hit.pickedPoint;
  75461. if (!contactPoint) {
  75462. return null;
  75463. }
  75464. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75465. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75466. var directionToOrigin = contactPoint.normalize();
  75467. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75468. directionToOrigin = directionToOrigin.negate();
  75469. }
  75470. // TODO: find a more physically based solution
  75471. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75472. var forceX = directionToOrigin.x * this._strength / 8;
  75473. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75474. var forceZ = directionToOrigin.z * this._strength / 8;
  75475. }
  75476. else {
  75477. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75478. var forceY = this._originTop.y * this._updraftMultiplier;
  75479. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75480. }
  75481. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75482. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75483. return { force: force, contactPoint: impostorObjectCenter };
  75484. };
  75485. PhysicsVortexEvent.prototype._tick = function () {
  75486. var _this = this;
  75487. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75488. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75489. if (!impostorForceAndContactPoint) {
  75490. return;
  75491. }
  75492. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75493. });
  75494. };
  75495. /*** Helpers ***/
  75496. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75497. if (!this._cylinder) {
  75498. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75499. height: this._height,
  75500. diameter: this._radius * 2,
  75501. }, this._scene);
  75502. this._cylinder.isVisible = false;
  75503. }
  75504. };
  75505. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75506. var impostorObject = impostor.object;
  75507. this._prepareCylinder();
  75508. this._cylinder.position = this._cylinderPosition;
  75509. return this._cylinder.intersectsMesh(impostorObject, true);
  75510. };
  75511. return PhysicsVortexEvent;
  75512. }());
  75513. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75514. /***** Enums *****/
  75515. /**
  75516. * The strenght of the force in correspondence to the distance of the affected object
  75517. */
  75518. var PhysicsRadialImpulseFalloff;
  75519. (function (PhysicsRadialImpulseFalloff) {
  75520. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75521. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75522. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75523. /**
  75524. * The strenght of the force in correspondence to the distance of the affected object
  75525. */
  75526. var PhysicsUpdraftMode;
  75527. (function (PhysicsUpdraftMode) {
  75528. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75529. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75530. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75531. })(BABYLON || (BABYLON = {}));
  75532. //# sourceMappingURL=babylon.physicsHelper.js.map
  75533. var BABYLON;
  75534. (function (BABYLON) {
  75535. var CannonJSPlugin = /** @class */ (function () {
  75536. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75537. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75538. if (iterations === void 0) { iterations = 10; }
  75539. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75540. this.name = "CannonJSPlugin";
  75541. this._physicsMaterials = new Array();
  75542. this._fixedTimeStep = 1 / 60;
  75543. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75544. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75545. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75546. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75547. this._tmpPosition = BABYLON.Vector3.Zero();
  75548. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75549. this._tmpUnityRotation = new BABYLON.Quaternion();
  75550. if (!this.isSupported()) {
  75551. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75552. return;
  75553. }
  75554. this._extendNamespace();
  75555. this.world = new this.BJSCANNON.World();
  75556. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75557. this.world.solver.iterations = iterations;
  75558. }
  75559. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75560. this.world.gravity.copy(gravity);
  75561. };
  75562. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75563. this._fixedTimeStep = timeStep;
  75564. };
  75565. CannonJSPlugin.prototype.getTimeStep = function () {
  75566. return this._fixedTimeStep;
  75567. };
  75568. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75569. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75570. };
  75571. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75572. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75573. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75574. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75575. };
  75576. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75577. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75578. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75579. impostor.physicsBody.applyForce(impulse, worldPoint);
  75580. };
  75581. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75582. //parent-child relationship. Does this impostor has a parent impostor?
  75583. if (impostor.parent) {
  75584. if (impostor.physicsBody) {
  75585. this.removePhysicsBody(impostor);
  75586. //TODO is that needed?
  75587. impostor.forceUpdate();
  75588. }
  75589. return;
  75590. }
  75591. //should a new body be created for this impostor?
  75592. if (impostor.isBodyInitRequired()) {
  75593. var shape = this._createShape(impostor);
  75594. //unregister events, if body is being changed
  75595. var oldBody = impostor.physicsBody;
  75596. if (oldBody) {
  75597. this.removePhysicsBody(impostor);
  75598. }
  75599. //create the body and material
  75600. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75601. var bodyCreationObject = {
  75602. mass: impostor.getParam("mass"),
  75603. material: material
  75604. };
  75605. // A simple extend, in case native options were used.
  75606. var nativeOptions = impostor.getParam("nativeOptions");
  75607. for (var key in nativeOptions) {
  75608. if (nativeOptions.hasOwnProperty(key)) {
  75609. bodyCreationObject[key] = nativeOptions[key];
  75610. }
  75611. }
  75612. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75613. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75614. this.world.addEventListener("preStep", impostor.beforeStep);
  75615. this.world.addEventListener("postStep", impostor.afterStep);
  75616. impostor.physicsBody.addShape(shape);
  75617. this.world.add(impostor.physicsBody);
  75618. //try to keep the body moving in the right direction by taking old properties.
  75619. //Should be tested!
  75620. if (oldBody) {
  75621. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75622. impostor.physicsBody[param].copy(oldBody[param]);
  75623. });
  75624. }
  75625. this._processChildMeshes(impostor);
  75626. }
  75627. //now update the body's transformation
  75628. this._updatePhysicsBodyTransformation(impostor);
  75629. };
  75630. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75631. var _this = this;
  75632. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75633. var currentRotation = mainImpostor.object.rotationQuaternion;
  75634. if (meshChildren.length) {
  75635. var processMesh = function (localPosition, mesh) {
  75636. if (!currentRotation || !mesh.rotationQuaternion) {
  75637. return;
  75638. }
  75639. var childImpostor = mesh.getPhysicsImpostor();
  75640. if (childImpostor) {
  75641. var parent = childImpostor.parent;
  75642. if (parent !== mainImpostor) {
  75643. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75644. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75645. if (childImpostor.physicsBody) {
  75646. _this.removePhysicsBody(childImpostor);
  75647. childImpostor.physicsBody = null;
  75648. }
  75649. childImpostor.parent = mainImpostor;
  75650. childImpostor.resetUpdateFlags();
  75651. 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));
  75652. //Add the mass of the children.
  75653. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75654. }
  75655. }
  75656. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75657. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75658. };
  75659. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75660. }
  75661. };
  75662. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75663. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75664. this.world.removeEventListener("preStep", impostor.beforeStep);
  75665. this.world.removeEventListener("postStep", impostor.afterStep);
  75666. this.world.remove(impostor.physicsBody);
  75667. };
  75668. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75669. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75670. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75671. if (!mainBody || !connectedBody) {
  75672. return;
  75673. }
  75674. var constraint;
  75675. var jointData = impostorJoint.joint.jointData;
  75676. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75677. var constraintData = {
  75678. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75679. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75680. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75681. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75682. maxForce: jointData.nativeParams.maxForce,
  75683. collideConnected: !!jointData.collision
  75684. };
  75685. switch (impostorJoint.joint.type) {
  75686. case BABYLON.PhysicsJoint.HingeJoint:
  75687. case BABYLON.PhysicsJoint.Hinge2Joint:
  75688. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  75689. break;
  75690. case BABYLON.PhysicsJoint.DistanceJoint:
  75691. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  75692. break;
  75693. case BABYLON.PhysicsJoint.SpringJoint:
  75694. var springData = jointData;
  75695. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  75696. restLength: springData.length,
  75697. stiffness: springData.stiffness,
  75698. damping: springData.damping,
  75699. localAnchorA: constraintData.pivotA,
  75700. localAnchorB: constraintData.pivotB
  75701. });
  75702. break;
  75703. case BABYLON.PhysicsJoint.LockJoint:
  75704. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  75705. break;
  75706. case BABYLON.PhysicsJoint.PointToPointJoint:
  75707. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75708. default:
  75709. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  75710. break;
  75711. }
  75712. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  75713. constraint.collideConnected = !!jointData.collision;
  75714. impostorJoint.joint.physicsJoint = constraint;
  75715. //don't add spring as constraint, as it is not one.
  75716. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  75717. this.world.addConstraint(constraint);
  75718. }
  75719. else {
  75720. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  75721. constraint.applyForce();
  75722. });
  75723. }
  75724. };
  75725. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75726. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  75727. };
  75728. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  75729. var index;
  75730. var mat;
  75731. for (index = 0; index < this._physicsMaterials.length; index++) {
  75732. mat = this._physicsMaterials[index];
  75733. if (mat.friction === friction && mat.restitution === restitution) {
  75734. return mat;
  75735. }
  75736. }
  75737. var currentMat = new this.BJSCANNON.Material(name);
  75738. currentMat.friction = friction;
  75739. currentMat.restitution = restitution;
  75740. this._physicsMaterials.push(currentMat);
  75741. return currentMat;
  75742. };
  75743. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  75744. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  75745. };
  75746. CannonJSPlugin.prototype._createShape = function (impostor) {
  75747. var object = impostor.object;
  75748. var returnValue;
  75749. var extendSize = impostor.getObjectExtendSize();
  75750. switch (impostor.type) {
  75751. case BABYLON.PhysicsImpostor.SphereImpostor:
  75752. var radiusX = extendSize.x;
  75753. var radiusY = extendSize.y;
  75754. var radiusZ = extendSize.z;
  75755. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  75756. break;
  75757. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  75758. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75759. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  75760. break;
  75761. case BABYLON.PhysicsImpostor.BoxImpostor:
  75762. var box = extendSize.scale(0.5);
  75763. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  75764. break;
  75765. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75766. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  75767. returnValue = new this.BJSCANNON.Plane();
  75768. break;
  75769. case BABYLON.PhysicsImpostor.MeshImpostor:
  75770. // should transform the vertex data to world coordinates!!
  75771. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  75772. var rawFaces = object.getIndices ? object.getIndices() : [];
  75773. if (!rawVerts)
  75774. return;
  75775. // get only scale! so the object could transform correctly.
  75776. var oldPosition = object.position.clone();
  75777. var oldRotation = object.rotation && object.rotation.clone();
  75778. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  75779. object.position.copyFromFloats(0, 0, 0);
  75780. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75781. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75782. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75783. var transform = object.computeWorldMatrix(true);
  75784. // convert rawVerts to object space
  75785. var temp = new Array();
  75786. var index;
  75787. for (index = 0; index < rawVerts.length; index += 3) {
  75788. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  75789. }
  75790. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  75791. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  75792. //now set back the transformation!
  75793. object.position.copyFrom(oldPosition);
  75794. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  75795. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  75796. break;
  75797. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  75798. var oldPosition2 = object.position.clone();
  75799. var oldRotation2 = object.rotation && object.rotation.clone();
  75800. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  75801. object.position.copyFromFloats(0, 0, 0);
  75802. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75803. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75804. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75805. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  75806. returnValue = this._createHeightmap(object);
  75807. object.position.copyFrom(oldPosition2);
  75808. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  75809. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  75810. object.computeWorldMatrix(true);
  75811. break;
  75812. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75813. returnValue = new this.BJSCANNON.Particle();
  75814. break;
  75815. }
  75816. return returnValue;
  75817. };
  75818. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  75819. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75820. var transform = object.computeWorldMatrix(true);
  75821. // convert rawVerts to object space
  75822. var temp = new Array();
  75823. var index;
  75824. for (index = 0; index < pos.length; index += 3) {
  75825. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  75826. }
  75827. pos = temp;
  75828. var matrix = new Array();
  75829. //For now pointDepth will not be used and will be automatically calculated.
  75830. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  75831. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  75832. var boundingInfo = object.getBoundingInfo();
  75833. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  75834. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  75835. var elementSize = dim * 2 / arraySize;
  75836. for (var i = 0; i < pos.length; i = i + 3) {
  75837. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  75838. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  75839. var y = -pos[i + 2] + minY;
  75840. if (!matrix[x]) {
  75841. matrix[x] = [];
  75842. }
  75843. if (!matrix[x][z]) {
  75844. matrix[x][z] = y;
  75845. }
  75846. matrix[x][z] = Math.max(y, matrix[x][z]);
  75847. }
  75848. for (var x = 0; x <= arraySize; ++x) {
  75849. if (!matrix[x]) {
  75850. var loc = 1;
  75851. while (!matrix[(x + loc) % arraySize]) {
  75852. loc++;
  75853. }
  75854. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75855. //console.log("missing x", x);
  75856. }
  75857. for (var z = 0; z <= arraySize; ++z) {
  75858. if (!matrix[x][z]) {
  75859. var loc = 1;
  75860. var newValue;
  75861. while (newValue === undefined) {
  75862. newValue = matrix[x][(z + loc++) % arraySize];
  75863. }
  75864. matrix[x][z] = newValue;
  75865. }
  75866. }
  75867. }
  75868. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75869. elementSize: elementSize
  75870. });
  75871. //For future reference, needed for body transformation
  75872. shape.minY = minY;
  75873. return shape;
  75874. };
  75875. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75876. var object = impostor.object;
  75877. //make sure it is updated...
  75878. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75879. // The delta between the mesh position and the mesh bounding box center
  75880. var bInfo = object.getBoundingInfo();
  75881. if (!bInfo)
  75882. return;
  75883. var center = impostor.getObjectCenter();
  75884. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75885. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75886. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75887. this._tmpPosition.copyFrom(center);
  75888. var quaternion = object.rotationQuaternion;
  75889. if (!quaternion) {
  75890. return;
  75891. }
  75892. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75893. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75894. //-90 DEG in X, precalculated
  75895. quaternion = quaternion.multiply(this._minus90X);
  75896. //Invert! (Precalculated, 90 deg in X)
  75897. //No need to clone. this will never change.
  75898. impostor.setDeltaRotation(this._plus90X);
  75899. }
  75900. //If it is a heightfield, if should be centered.
  75901. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75902. var mesh = object;
  75903. var boundingInfo = mesh.getBoundingInfo();
  75904. //calculate the correct body position:
  75905. var rotationQuaternion = mesh.rotationQuaternion;
  75906. mesh.rotationQuaternion = this._tmpUnityRotation;
  75907. mesh.computeWorldMatrix(true);
  75908. //get original center with no rotation
  75909. var c = center.clone();
  75910. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75911. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75912. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75913. mesh.setPreTransformMatrix(p);
  75914. mesh.computeWorldMatrix(true);
  75915. //calculate the translation
  75916. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75917. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75918. //add it inverted to the delta
  75919. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75920. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75921. //rotation is back
  75922. mesh.rotationQuaternion = rotationQuaternion;
  75923. mesh.setPreTransformMatrix(oldPivot);
  75924. mesh.computeWorldMatrix(true);
  75925. }
  75926. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75927. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75928. //this._tmpPosition.copyFrom(object.position);
  75929. }
  75930. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75931. //Now update the impostor object
  75932. impostor.physicsBody.position.copy(this._tmpPosition);
  75933. impostor.physicsBody.quaternion.copy(quaternion);
  75934. };
  75935. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75936. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75937. if (impostor.object.rotationQuaternion) {
  75938. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75939. }
  75940. };
  75941. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75942. impostor.physicsBody.position.copy(newPosition);
  75943. impostor.physicsBody.quaternion.copy(newRotation);
  75944. };
  75945. CannonJSPlugin.prototype.isSupported = function () {
  75946. return this.BJSCANNON !== undefined;
  75947. };
  75948. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75949. impostor.physicsBody.velocity.copy(velocity);
  75950. };
  75951. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75952. impostor.physicsBody.angularVelocity.copy(velocity);
  75953. };
  75954. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75955. var v = impostor.physicsBody.velocity;
  75956. if (!v) {
  75957. return null;
  75958. }
  75959. return new BABYLON.Vector3(v.x, v.y, v.z);
  75960. };
  75961. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75962. var v = impostor.physicsBody.angularVelocity;
  75963. if (!v) {
  75964. return null;
  75965. }
  75966. return new BABYLON.Vector3(v.x, v.y, v.z);
  75967. };
  75968. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75969. impostor.physicsBody.mass = mass;
  75970. impostor.physicsBody.updateMassProperties();
  75971. };
  75972. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75973. return impostor.physicsBody.mass;
  75974. };
  75975. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75976. return impostor.physicsBody.material.friction;
  75977. };
  75978. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75979. impostor.physicsBody.material.friction = friction;
  75980. };
  75981. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75982. return impostor.physicsBody.material.restitution;
  75983. };
  75984. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75985. impostor.physicsBody.material.restitution = restitution;
  75986. };
  75987. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75988. impostor.physicsBody.sleep();
  75989. };
  75990. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75991. impostor.physicsBody.wakeUp();
  75992. };
  75993. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75994. joint.physicsJoint.distance = maxDistance;
  75995. };
  75996. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75997. // if (!motorIndex) {
  75998. // joint.physicsJoint.enableMotor();
  75999. // }
  76000. // }
  76001. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76002. // if (!motorIndex) {
  76003. // joint.physicsJoint.disableMotor();
  76004. // }
  76005. // }
  76006. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76007. if (!motorIndex) {
  76008. joint.physicsJoint.enableMotor();
  76009. joint.physicsJoint.setMotorSpeed(speed);
  76010. if (maxForce) {
  76011. this.setLimit(joint, maxForce);
  76012. }
  76013. }
  76014. };
  76015. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76016. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76017. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76018. };
  76019. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76020. var body = impostor.physicsBody;
  76021. mesh.position.x = body.position.x;
  76022. mesh.position.y = body.position.y;
  76023. mesh.position.z = body.position.z;
  76024. if (mesh.rotationQuaternion) {
  76025. mesh.rotationQuaternion.x = body.quaternion.x;
  76026. mesh.rotationQuaternion.y = body.quaternion.y;
  76027. mesh.rotationQuaternion.z = body.quaternion.z;
  76028. mesh.rotationQuaternion.w = body.quaternion.w;
  76029. }
  76030. };
  76031. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76032. var shape = impostor.physicsBody.shapes[0];
  76033. return shape.boundingSphereRadius;
  76034. };
  76035. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76036. var shape = impostor.physicsBody.shapes[0];
  76037. result.x = shape.halfExtents.x * 2;
  76038. result.y = shape.halfExtents.y * 2;
  76039. result.z = shape.halfExtents.z * 2;
  76040. };
  76041. CannonJSPlugin.prototype.dispose = function () {
  76042. };
  76043. CannonJSPlugin.prototype._extendNamespace = function () {
  76044. //this will force cannon to execute at least one step when using interpolation
  76045. var step_tmp1 = new this.BJSCANNON.Vec3();
  76046. var Engine = this.BJSCANNON;
  76047. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76048. maxSubSteps = maxSubSteps || 10;
  76049. timeSinceLastCalled = timeSinceLastCalled || 0;
  76050. if (timeSinceLastCalled === 0) {
  76051. this.internalStep(dt);
  76052. this.time += dt;
  76053. }
  76054. else {
  76055. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76056. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76057. var t0 = performance.now();
  76058. for (var i = 0; i !== internalSteps; i++) {
  76059. this.internalStep(dt);
  76060. if (performance.now() - t0 > dt * 1000) {
  76061. break;
  76062. }
  76063. }
  76064. this.time += timeSinceLastCalled;
  76065. var h = this.time % dt;
  76066. var h_div_dt = h / dt;
  76067. var interpvelo = step_tmp1;
  76068. var bodies = this.bodies;
  76069. for (var j = 0; j !== bodies.length; j++) {
  76070. var b = bodies[j];
  76071. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76072. b.position.vsub(b.previousPosition, interpvelo);
  76073. interpvelo.scale(h_div_dt, interpvelo);
  76074. b.position.vadd(interpvelo, b.interpolatedPosition);
  76075. }
  76076. else {
  76077. b.interpolatedPosition.copy(b.position);
  76078. b.interpolatedQuaternion.copy(b.quaternion);
  76079. }
  76080. }
  76081. }
  76082. };
  76083. };
  76084. return CannonJSPlugin;
  76085. }());
  76086. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76087. })(BABYLON || (BABYLON = {}));
  76088. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76089. var BABYLON;
  76090. (function (BABYLON) {
  76091. var OimoJSPlugin = /** @class */ (function () {
  76092. function OimoJSPlugin(iterations) {
  76093. this.name = "OimoJSPlugin";
  76094. this._tmpImpostorsArray = [];
  76095. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76096. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76097. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76098. this.world.worldscale(1);
  76099. this.world.clear();
  76100. //making sure no stats are calculated
  76101. this.world.isNoStat = true;
  76102. }
  76103. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76104. this.world.gravity.copy(gravity);
  76105. };
  76106. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76107. this.world.timeStep = timeStep;
  76108. };
  76109. OimoJSPlugin.prototype.getTimeStep = function () {
  76110. return this.world.timeStep;
  76111. };
  76112. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76113. var _this = this;
  76114. impostors.forEach(function (impostor) {
  76115. impostor.beforeStep();
  76116. });
  76117. this.world.step();
  76118. impostors.forEach(function (impostor) {
  76119. impostor.afterStep();
  76120. //update the ordered impostors array
  76121. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76122. });
  76123. //check for collisions
  76124. var contact = this.world.contacts;
  76125. while (contact !== null) {
  76126. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76127. contact = contact.next;
  76128. continue;
  76129. }
  76130. //is this body colliding with any other? get the impostor
  76131. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76132. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76133. if (!mainImpostor || !collidingImpostor) {
  76134. contact = contact.next;
  76135. continue;
  76136. }
  76137. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76138. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76139. contact = contact.next;
  76140. }
  76141. };
  76142. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76143. var mass = impostor.physicsBody.massInfo.mass;
  76144. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76145. };
  76146. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76147. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76148. this.applyImpulse(impostor, force, contactPoint);
  76149. };
  76150. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76151. var _this = this;
  76152. //parent-child relationship. Does this impostor has a parent impostor?
  76153. if (impostor.parent) {
  76154. if (impostor.physicsBody) {
  76155. this.removePhysicsBody(impostor);
  76156. //TODO is that needed?
  76157. impostor.forceUpdate();
  76158. }
  76159. return;
  76160. }
  76161. if (impostor.isBodyInitRequired()) {
  76162. var bodyConfig = {
  76163. name: impostor.uniqueId,
  76164. //Oimo must have mass, also for static objects.
  76165. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76166. size: [],
  76167. type: [],
  76168. pos: [],
  76169. rot: [],
  76170. move: impostor.getParam("mass") !== 0,
  76171. //Supporting older versions of Oimo
  76172. world: this.world
  76173. };
  76174. var impostors = [impostor];
  76175. var addToArray = function (parent) {
  76176. if (!parent.getChildMeshes)
  76177. return;
  76178. parent.getChildMeshes().forEach(function (m) {
  76179. if (m.physicsImpostor) {
  76180. impostors.push(m.physicsImpostor);
  76181. //m.physicsImpostor._init();
  76182. }
  76183. });
  76184. };
  76185. addToArray(impostor.object);
  76186. var checkWithEpsilon_1 = function (value) {
  76187. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76188. };
  76189. impostors.forEach(function (i) {
  76190. if (!impostor.object.rotationQuaternion) {
  76191. return;
  76192. }
  76193. //get the correct bounding box
  76194. var oldQuaternion = i.object.rotationQuaternion;
  76195. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76196. x: impostor.object.rotationQuaternion.x,
  76197. y: impostor.object.rotationQuaternion.y,
  76198. z: impostor.object.rotationQuaternion.z,
  76199. s: impostor.object.rotationQuaternion.w
  76200. });
  76201. var extendSize = i.getObjectExtendSize();
  76202. if (i === impostor) {
  76203. var center = impostor.getObjectCenter();
  76204. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76205. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76206. //Can also use Array.prototype.push.apply
  76207. bodyConfig.pos.push(center.x);
  76208. bodyConfig.pos.push(center.y);
  76209. bodyConfig.pos.push(center.z);
  76210. //tmp solution
  76211. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76212. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76213. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76214. }
  76215. else {
  76216. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76217. bodyConfig.pos.push(localPosition.x);
  76218. bodyConfig.pos.push(localPosition.y);
  76219. bodyConfig.pos.push(localPosition.z);
  76220. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76221. bodyConfig.rot.push(0);
  76222. bodyConfig.rot.push(0);
  76223. bodyConfig.rot.push(0);
  76224. }
  76225. // register mesh
  76226. switch (i.type) {
  76227. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76228. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76229. case BABYLON.PhysicsImpostor.SphereImpostor:
  76230. var radiusX = extendSize.x;
  76231. var radiusY = extendSize.y;
  76232. var radiusZ = extendSize.z;
  76233. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76234. bodyConfig.type.push('sphere');
  76235. //due to the way oimo works with compounds, add 3 times
  76236. bodyConfig.size.push(size);
  76237. bodyConfig.size.push(size);
  76238. bodyConfig.size.push(size);
  76239. break;
  76240. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76241. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76242. var sizeY = checkWithEpsilon_1(extendSize.y);
  76243. bodyConfig.type.push('cylinder');
  76244. bodyConfig.size.push(sizeX);
  76245. bodyConfig.size.push(sizeY);
  76246. //due to the way oimo works with compounds, add one more value.
  76247. bodyConfig.size.push(sizeY);
  76248. break;
  76249. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76250. case BABYLON.PhysicsImpostor.BoxImpostor:
  76251. default:
  76252. var sizeX = checkWithEpsilon_1(extendSize.x);
  76253. var sizeY = checkWithEpsilon_1(extendSize.y);
  76254. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76255. bodyConfig.type.push('box');
  76256. bodyConfig.size.push(sizeX);
  76257. bodyConfig.size.push(sizeY);
  76258. bodyConfig.size.push(sizeZ);
  76259. break;
  76260. }
  76261. //actually not needed, but hey...
  76262. i.object.rotationQuaternion = oldQuaternion;
  76263. });
  76264. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76265. }
  76266. else {
  76267. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76268. }
  76269. impostor.setDeltaPosition(this._tmpPositionVector);
  76270. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76271. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76272. };
  76273. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76274. //impostor.physicsBody.dispose();
  76275. //Same as : (older oimo versions)
  76276. this.world.removeRigidBody(impostor.physicsBody);
  76277. };
  76278. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76279. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76280. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76281. if (!mainBody || !connectedBody) {
  76282. return;
  76283. }
  76284. var jointData = impostorJoint.joint.jointData;
  76285. var options = jointData.nativeParams || {};
  76286. var type;
  76287. var nativeJointData = {
  76288. body1: mainBody,
  76289. body2: connectedBody,
  76290. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76291. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76292. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76293. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76294. min: options.min,
  76295. max: options.max,
  76296. collision: options.collision || jointData.collision,
  76297. spring: options.spring,
  76298. //supporting older version of Oimo
  76299. world: this.world
  76300. };
  76301. switch (impostorJoint.joint.type) {
  76302. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76303. type = "jointBall";
  76304. break;
  76305. case BABYLON.PhysicsJoint.SpringJoint:
  76306. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76307. var springData = jointData;
  76308. nativeJointData.min = springData.length || nativeJointData.min;
  76309. //Max should also be set, just make sure it is at least min
  76310. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76311. case BABYLON.PhysicsJoint.DistanceJoint:
  76312. type = "jointDistance";
  76313. nativeJointData.max = jointData.maxDistance;
  76314. break;
  76315. case BABYLON.PhysicsJoint.PrismaticJoint:
  76316. type = "jointPrisme";
  76317. break;
  76318. case BABYLON.PhysicsJoint.SliderJoint:
  76319. type = "jointSlide";
  76320. break;
  76321. case BABYLON.PhysicsJoint.WheelJoint:
  76322. type = "jointWheel";
  76323. break;
  76324. case BABYLON.PhysicsJoint.HingeJoint:
  76325. default:
  76326. type = "jointHinge";
  76327. break;
  76328. }
  76329. nativeJointData.type = type;
  76330. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76331. };
  76332. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76333. //Bug in Oimo prevents us from disposing a joint in the playground
  76334. //joint.joint.physicsJoint.dispose();
  76335. //So we will bruteforce it!
  76336. try {
  76337. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76338. }
  76339. catch (e) {
  76340. BABYLON.Tools.Warn(e);
  76341. }
  76342. };
  76343. OimoJSPlugin.prototype.isSupported = function () {
  76344. return this.BJSOIMO !== undefined;
  76345. };
  76346. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76347. if (!impostor.physicsBody.sleeping) {
  76348. //TODO check that
  76349. if (impostor.physicsBody.shapes.next) {
  76350. var parentShape = this._getLastShape(impostor.physicsBody);
  76351. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76352. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76353. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76354. }
  76355. else {
  76356. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76357. }
  76358. if (impostor.object.rotationQuaternion) {
  76359. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76360. impostor.object.rotationQuaternion.normalize();
  76361. }
  76362. }
  76363. };
  76364. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76365. var body = impostor.physicsBody;
  76366. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76367. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76368. body.syncShapes();
  76369. body.awake();
  76370. };
  76371. OimoJSPlugin.prototype._getLastShape = function (body) {
  76372. var lastShape = body.shapes;
  76373. while (lastShape.next) {
  76374. lastShape = lastShape.next;
  76375. }
  76376. return lastShape;
  76377. };
  76378. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76379. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76380. };
  76381. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76382. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76383. };
  76384. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76385. var v = impostor.physicsBody.linearVelocity;
  76386. if (!v) {
  76387. return null;
  76388. }
  76389. return new BABYLON.Vector3(v.x, v.y, v.z);
  76390. };
  76391. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76392. var v = impostor.physicsBody.angularVelocity;
  76393. if (!v) {
  76394. return null;
  76395. }
  76396. return new BABYLON.Vector3(v.x, v.y, v.z);
  76397. };
  76398. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76399. var staticBody = mass === 0;
  76400. //this will actually set the body's density and not its mass.
  76401. //But this is how oimo treats the mass variable.
  76402. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76403. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76404. };
  76405. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76406. return impostor.physicsBody.shapes.density;
  76407. };
  76408. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76409. return impostor.physicsBody.shapes.friction;
  76410. };
  76411. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76412. impostor.physicsBody.shapes.friction = friction;
  76413. };
  76414. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76415. return impostor.physicsBody.shapes.restitution;
  76416. };
  76417. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76418. impostor.physicsBody.shapes.restitution = restitution;
  76419. };
  76420. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76421. impostor.physicsBody.sleep();
  76422. };
  76423. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76424. impostor.physicsBody.awake();
  76425. };
  76426. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76427. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76428. if (minDistance !== void 0) {
  76429. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76430. }
  76431. };
  76432. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76433. //TODO separate rotational and transational motors.
  76434. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76435. if (motor) {
  76436. motor.setMotor(speed, maxForce);
  76437. }
  76438. };
  76439. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76440. //TODO separate rotational and transational motors.
  76441. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76442. if (motor) {
  76443. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76444. }
  76445. };
  76446. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76447. var body = impostor.physicsBody;
  76448. mesh.position.x = body.position.x;
  76449. mesh.position.y = body.position.y;
  76450. mesh.position.z = body.position.z;
  76451. if (mesh.rotationQuaternion) {
  76452. mesh.rotationQuaternion.x = body.orientation.x;
  76453. mesh.rotationQuaternion.y = body.orientation.y;
  76454. mesh.rotationQuaternion.z = body.orientation.z;
  76455. mesh.rotationQuaternion.w = body.orientation.s;
  76456. }
  76457. };
  76458. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76459. return impostor.physicsBody.shapes.radius;
  76460. };
  76461. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76462. var shape = impostor.physicsBody.shapes;
  76463. result.x = shape.halfWidth * 2;
  76464. result.y = shape.halfHeight * 2;
  76465. result.z = shape.halfDepth * 2;
  76466. };
  76467. OimoJSPlugin.prototype.dispose = function () {
  76468. this.world.clear();
  76469. };
  76470. return OimoJSPlugin;
  76471. }());
  76472. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76473. })(BABYLON || (BABYLON = {}));
  76474. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76475. var BABYLON;
  76476. (function (BABYLON) {
  76477. /*
  76478. * Based on jsTGALoader - Javascript loader for TGA file
  76479. * By Vincent Thibault
  76480. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76481. */
  76482. var TGATools = /** @class */ (function () {
  76483. function TGATools() {
  76484. }
  76485. TGATools.GetTGAHeader = function (data) {
  76486. var offset = 0;
  76487. var header = {
  76488. id_length: data[offset++],
  76489. colormap_type: data[offset++],
  76490. image_type: data[offset++],
  76491. colormap_index: data[offset++] | data[offset++] << 8,
  76492. colormap_length: data[offset++] | data[offset++] << 8,
  76493. colormap_size: data[offset++],
  76494. origin: [
  76495. data[offset++] | data[offset++] << 8,
  76496. data[offset++] | data[offset++] << 8
  76497. ],
  76498. width: data[offset++] | data[offset++] << 8,
  76499. height: data[offset++] | data[offset++] << 8,
  76500. pixel_size: data[offset++],
  76501. flags: data[offset++]
  76502. };
  76503. return header;
  76504. };
  76505. TGATools.UploadContent = function (gl, data) {
  76506. // Not enough data to contain header ?
  76507. if (data.length < 19) {
  76508. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76509. return;
  76510. }
  76511. // Read Header
  76512. var offset = 18;
  76513. var header = TGATools.GetTGAHeader(data);
  76514. // Assume it's a valid Targa file.
  76515. if (header.id_length + offset > data.length) {
  76516. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76517. return;
  76518. }
  76519. // Skip not needed data
  76520. offset += header.id_length;
  76521. var use_rle = false;
  76522. var use_pal = false;
  76523. var use_grey = false;
  76524. // Get some informations.
  76525. switch (header.image_type) {
  76526. case TGATools._TYPE_RLE_INDEXED:
  76527. use_rle = true;
  76528. case TGATools._TYPE_INDEXED:
  76529. use_pal = true;
  76530. break;
  76531. case TGATools._TYPE_RLE_RGB:
  76532. use_rle = true;
  76533. case TGATools._TYPE_RGB:
  76534. // use_rgb = true;
  76535. break;
  76536. case TGATools._TYPE_RLE_GREY:
  76537. use_rle = true;
  76538. case TGATools._TYPE_GREY:
  76539. use_grey = true;
  76540. break;
  76541. }
  76542. var pixel_data;
  76543. // var numAlphaBits = header.flags & 0xf;
  76544. var pixel_size = header.pixel_size >> 3;
  76545. var pixel_total = header.width * header.height * pixel_size;
  76546. // Read palettes
  76547. var palettes;
  76548. if (use_pal) {
  76549. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76550. }
  76551. // Read LRE
  76552. if (use_rle) {
  76553. pixel_data = new Uint8Array(pixel_total);
  76554. var c, count, i;
  76555. var localOffset = 0;
  76556. var pixels = new Uint8Array(pixel_size);
  76557. while (offset < pixel_total && localOffset < pixel_total) {
  76558. c = data[offset++];
  76559. count = (c & 0x7f) + 1;
  76560. // RLE pixels
  76561. if (c & 0x80) {
  76562. // Bind pixel tmp array
  76563. for (i = 0; i < pixel_size; ++i) {
  76564. pixels[i] = data[offset++];
  76565. }
  76566. // Copy pixel array
  76567. for (i = 0; i < count; ++i) {
  76568. pixel_data.set(pixels, localOffset + i * pixel_size);
  76569. }
  76570. localOffset += pixel_size * count;
  76571. }
  76572. else {
  76573. count *= pixel_size;
  76574. for (i = 0; i < count; ++i) {
  76575. pixel_data[localOffset + i] = data[offset++];
  76576. }
  76577. localOffset += count;
  76578. }
  76579. }
  76580. }
  76581. else {
  76582. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76583. }
  76584. // Load to texture
  76585. var x_start, y_start, x_step, y_step, y_end, x_end;
  76586. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76587. default:
  76588. case TGATools._ORIGIN_UL:
  76589. x_start = 0;
  76590. x_step = 1;
  76591. x_end = header.width;
  76592. y_start = 0;
  76593. y_step = 1;
  76594. y_end = header.height;
  76595. break;
  76596. case TGATools._ORIGIN_BL:
  76597. x_start = 0;
  76598. x_step = 1;
  76599. x_end = header.width;
  76600. y_start = header.height - 1;
  76601. y_step = -1;
  76602. y_end = -1;
  76603. break;
  76604. case TGATools._ORIGIN_UR:
  76605. x_start = header.width - 1;
  76606. x_step = -1;
  76607. x_end = -1;
  76608. y_start = 0;
  76609. y_step = 1;
  76610. y_end = header.height;
  76611. break;
  76612. case TGATools._ORIGIN_BR:
  76613. x_start = header.width - 1;
  76614. x_step = -1;
  76615. x_end = -1;
  76616. y_start = header.height - 1;
  76617. y_step = -1;
  76618. y_end = -1;
  76619. break;
  76620. }
  76621. // Load the specify method
  76622. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76623. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76625. };
  76626. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76627. var image = pixel_data, colormap = palettes;
  76628. var width = header.width, height = header.height;
  76629. var color, i = 0, x, y;
  76630. var imageData = new Uint8Array(width * height * 4);
  76631. for (y = y_start; y !== y_end; y += y_step) {
  76632. for (x = x_start; x !== x_end; x += x_step, i++) {
  76633. color = image[i];
  76634. imageData[(x + width * y) * 4 + 3] = 255;
  76635. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76636. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76637. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76638. }
  76639. }
  76640. return imageData;
  76641. };
  76642. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76643. var image = pixel_data;
  76644. var width = header.width, height = header.height;
  76645. var color, i = 0, x, y;
  76646. var imageData = new Uint8Array(width * height * 4);
  76647. for (y = y_start; y !== y_end; y += y_step) {
  76648. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76649. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76650. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76651. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76652. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76653. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76654. }
  76655. }
  76656. return imageData;
  76657. };
  76658. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76659. var image = pixel_data;
  76660. var width = header.width, height = header.height;
  76661. var i = 0, x, y;
  76662. var imageData = new Uint8Array(width * height * 4);
  76663. for (y = y_start; y !== y_end; y += y_step) {
  76664. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76665. imageData[(x + width * y) * 4 + 3] = 255;
  76666. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76667. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76668. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76669. }
  76670. }
  76671. return imageData;
  76672. };
  76673. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76674. var image = pixel_data;
  76675. var width = header.width, height = header.height;
  76676. var i = 0, x, y;
  76677. var imageData = new Uint8Array(width * height * 4);
  76678. for (y = y_start; y !== y_end; y += y_step) {
  76679. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76681. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76682. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76683. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76684. }
  76685. }
  76686. return imageData;
  76687. };
  76688. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76689. var image = pixel_data;
  76690. var width = header.width, height = header.height;
  76691. var color, i = 0, x, y;
  76692. var imageData = new Uint8Array(width * height * 4);
  76693. for (y = y_start; y !== y_end; y += y_step) {
  76694. for (x = x_start; x !== x_end; x += x_step, i++) {
  76695. color = image[i];
  76696. imageData[(x + width * y) * 4 + 0] = color;
  76697. imageData[(x + width * y) * 4 + 1] = color;
  76698. imageData[(x + width * y) * 4 + 2] = color;
  76699. imageData[(x + width * y) * 4 + 3] = 255;
  76700. }
  76701. }
  76702. return imageData;
  76703. };
  76704. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76705. var image = pixel_data;
  76706. var width = header.width, height = header.height;
  76707. var i = 0, x, y;
  76708. var imageData = new Uint8Array(width * height * 4);
  76709. for (y = y_start; y !== y_end; y += y_step) {
  76710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76711. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  76712. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  76713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76714. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  76715. }
  76716. }
  76717. return imageData;
  76718. };
  76719. //private static _TYPE_NO_DATA = 0;
  76720. TGATools._TYPE_INDEXED = 1;
  76721. TGATools._TYPE_RGB = 2;
  76722. TGATools._TYPE_GREY = 3;
  76723. TGATools._TYPE_RLE_INDEXED = 9;
  76724. TGATools._TYPE_RLE_RGB = 10;
  76725. TGATools._TYPE_RLE_GREY = 11;
  76726. TGATools._ORIGIN_MASK = 0x30;
  76727. TGATools._ORIGIN_SHIFT = 0x04;
  76728. TGATools._ORIGIN_BL = 0x00;
  76729. TGATools._ORIGIN_BR = 0x01;
  76730. TGATools._ORIGIN_UL = 0x02;
  76731. TGATools._ORIGIN_UR = 0x03;
  76732. return TGATools;
  76733. }());
  76734. BABYLON.TGATools = TGATools;
  76735. })(BABYLON || (BABYLON = {}));
  76736. //# sourceMappingURL=babylon.tga.js.map
  76737. var BABYLON;
  76738. (function (BABYLON) {
  76739. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  76740. // All values and structures referenced from:
  76741. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  76742. var DDS_MAGIC = 0x20534444;
  76743. var
  76744. //DDSD_CAPS = 0x1,
  76745. //DDSD_HEIGHT = 0x2,
  76746. //DDSD_WIDTH = 0x4,
  76747. //DDSD_PITCH = 0x8,
  76748. //DDSD_PIXELFORMAT = 0x1000,
  76749. DDSD_MIPMAPCOUNT = 0x20000;
  76750. //DDSD_LINEARSIZE = 0x80000,
  76751. //DDSD_DEPTH = 0x800000;
  76752. // var DDSCAPS_COMPLEX = 0x8,
  76753. // DDSCAPS_MIPMAP = 0x400000,
  76754. // DDSCAPS_TEXTURE = 0x1000;
  76755. var DDSCAPS2_CUBEMAP = 0x200;
  76756. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  76757. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  76758. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  76759. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  76760. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  76761. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  76762. // DDSCAPS2_VOLUME = 0x200000;
  76763. var
  76764. //DDPF_ALPHAPIXELS = 0x1,
  76765. //DDPF_ALPHA = 0x2,
  76766. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  76767. //DDPF_YUV = 0x200,
  76768. DDPF_LUMINANCE = 0x20000;
  76769. function FourCCToInt32(value) {
  76770. return value.charCodeAt(0) +
  76771. (value.charCodeAt(1) << 8) +
  76772. (value.charCodeAt(2) << 16) +
  76773. (value.charCodeAt(3) << 24);
  76774. }
  76775. function Int32ToFourCC(value) {
  76776. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  76777. }
  76778. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  76779. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  76780. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  76781. var FOURCC_DX10 = FourCCToInt32("DX10");
  76782. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  76783. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  76784. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  76785. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  76786. var headerLengthInt = 31; // The header length in 32 bit ints
  76787. // Offsets into the header array
  76788. var off_magic = 0;
  76789. var off_size = 1;
  76790. var off_flags = 2;
  76791. var off_height = 3;
  76792. var off_width = 4;
  76793. var off_mipmapCount = 7;
  76794. var off_pfFlags = 20;
  76795. var off_pfFourCC = 21;
  76796. var off_RGBbpp = 22;
  76797. var off_RMask = 23;
  76798. var off_GMask = 24;
  76799. var off_BMask = 25;
  76800. var off_AMask = 26;
  76801. // var off_caps1 = 27;
  76802. var off_caps2 = 28;
  76803. // var off_caps3 = 29;
  76804. // var off_caps4 = 30;
  76805. var off_dxgiFormat = 32;
  76806. ;
  76807. var DDSTools = /** @class */ (function () {
  76808. function DDSTools() {
  76809. }
  76810. DDSTools.GetDDSInfo = function (arrayBuffer) {
  76811. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76812. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  76813. var mipmapCount = 1;
  76814. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  76815. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76816. }
  76817. var fourCC = header[off_pfFourCC];
  76818. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  76819. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76820. switch (fourCC) {
  76821. case FOURCC_D3DFMT_R16G16B16A16F:
  76822. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76823. break;
  76824. case FOURCC_D3DFMT_R32G32B32A32F:
  76825. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76826. break;
  76827. case FOURCC_DX10:
  76828. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  76829. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76830. break;
  76831. }
  76832. }
  76833. return {
  76834. width: header[off_width],
  76835. height: header[off_height],
  76836. mipmapCount: mipmapCount,
  76837. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  76838. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  76839. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  76840. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  76841. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  76842. dxgiFormat: dxgiFormat,
  76843. textureType: textureType
  76844. };
  76845. };
  76846. DDSTools._ToHalfFloat = function (value) {
  76847. if (!DDSTools._FloatView) {
  76848. DDSTools._FloatView = new Float32Array(1);
  76849. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76850. }
  76851. DDSTools._FloatView[0] = value;
  76852. var x = DDSTools._Int32View[0];
  76853. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76854. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76855. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76856. /* If zero, or denormal, or exponent underflows too much for a denormal
  76857. * half, return signed zero. */
  76858. if (e < 103) {
  76859. return bits;
  76860. }
  76861. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76862. if (e > 142) {
  76863. bits |= 0x7c00;
  76864. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76865. * not Inf, so make sure we set one mantissa bit too. */
  76866. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76867. return bits;
  76868. }
  76869. /* If exponent underflows but not too much, return a denormal */
  76870. if (e < 113) {
  76871. m |= 0x0800;
  76872. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76873. * to 1, which is OK. */
  76874. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76875. return bits;
  76876. }
  76877. bits |= ((e - 112) << 10) | (m >> 1);
  76878. bits += m & 1;
  76879. return bits;
  76880. };
  76881. DDSTools._FromHalfFloat = function (value) {
  76882. var s = (value & 0x8000) >> 15;
  76883. var e = (value & 0x7C00) >> 10;
  76884. var f = value & 0x03FF;
  76885. if (e === 0) {
  76886. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76887. }
  76888. else if (e == 0x1F) {
  76889. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76890. }
  76891. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76892. };
  76893. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76894. var destArray = new Float32Array(dataLength);
  76895. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76896. var index = 0;
  76897. for (var y = 0; y < height; y++) {
  76898. for (var x = 0; x < width; x++) {
  76899. var srcPos = (x + y * width) * 4;
  76900. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76901. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76902. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76903. if (DDSTools.StoreLODInAlphaChannel) {
  76904. destArray[index + 3] = lod;
  76905. }
  76906. else {
  76907. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76908. }
  76909. index += 4;
  76910. }
  76911. }
  76912. return destArray;
  76913. };
  76914. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76915. if (DDSTools.StoreLODInAlphaChannel) {
  76916. var destArray = new Uint16Array(dataLength);
  76917. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76918. var index = 0;
  76919. for (var y = 0; y < height; y++) {
  76920. for (var x = 0; x < width; x++) {
  76921. var srcPos = (x + y * width) * 4;
  76922. destArray[index] = srcData[srcPos];
  76923. destArray[index + 1] = srcData[srcPos + 1];
  76924. destArray[index + 2] = srcData[srcPos + 2];
  76925. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76926. index += 4;
  76927. }
  76928. }
  76929. return destArray;
  76930. }
  76931. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76932. };
  76933. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76934. if (DDSTools.StoreLODInAlphaChannel) {
  76935. var destArray = new Float32Array(dataLength);
  76936. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76937. var index = 0;
  76938. for (var y = 0; y < height; y++) {
  76939. for (var x = 0; x < width; x++) {
  76940. var srcPos = (x + y * width) * 4;
  76941. destArray[index] = srcData[srcPos];
  76942. destArray[index + 1] = srcData[srcPos + 1];
  76943. destArray[index + 2] = srcData[srcPos + 2];
  76944. destArray[index + 3] = lod;
  76945. index += 4;
  76946. }
  76947. }
  76948. return destArray;
  76949. }
  76950. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76951. };
  76952. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76953. var destArray = new Uint8Array(dataLength);
  76954. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76955. var index = 0;
  76956. for (var y = 0; y < height; y++) {
  76957. for (var x = 0; x < width; x++) {
  76958. var srcPos = (x + y * width) * 4;
  76959. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76960. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76961. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76962. if (DDSTools.StoreLODInAlphaChannel) {
  76963. destArray[index + 3] = lod;
  76964. }
  76965. else {
  76966. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76967. }
  76968. index += 4;
  76969. }
  76970. }
  76971. return destArray;
  76972. };
  76973. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76974. var destArray = new Uint8Array(dataLength);
  76975. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76976. var index = 0;
  76977. for (var y = 0; y < height; y++) {
  76978. for (var x = 0; x < width; x++) {
  76979. var srcPos = (x + y * width) * 4;
  76980. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76981. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76982. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76983. if (DDSTools.StoreLODInAlphaChannel) {
  76984. destArray[index + 3] = lod;
  76985. }
  76986. else {
  76987. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76988. }
  76989. index += 4;
  76990. }
  76991. }
  76992. return destArray;
  76993. };
  76994. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76995. var byteArray = new Uint8Array(dataLength);
  76996. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76997. var index = 0;
  76998. for (var y = 0; y < height; y++) {
  76999. for (var x = 0; x < width; x++) {
  77000. var srcPos = (x + y * width) * 4;
  77001. byteArray[index] = srcData[srcPos + rOffset];
  77002. byteArray[index + 1] = srcData[srcPos + gOffset];
  77003. byteArray[index + 2] = srcData[srcPos + bOffset];
  77004. byteArray[index + 3] = srcData[srcPos + aOffset];
  77005. index += 4;
  77006. }
  77007. }
  77008. return byteArray;
  77009. };
  77010. DDSTools._ExtractLongWordOrder = function (value) {
  77011. if (value === 0 || value === 255 || value === -16777216) {
  77012. return 0;
  77013. }
  77014. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77015. };
  77016. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77017. var byteArray = new Uint8Array(dataLength);
  77018. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77019. var index = 0;
  77020. for (var y = 0; y < height; y++) {
  77021. for (var x = 0; x < width; x++) {
  77022. var srcPos = (x + y * width) * 3;
  77023. byteArray[index] = srcData[srcPos + rOffset];
  77024. byteArray[index + 1] = srcData[srcPos + gOffset];
  77025. byteArray[index + 2] = srcData[srcPos + bOffset];
  77026. index += 3;
  77027. }
  77028. }
  77029. return byteArray;
  77030. };
  77031. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77032. var byteArray = new Uint8Array(dataLength);
  77033. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77034. var index = 0;
  77035. for (var y = 0; y < height; y++) {
  77036. for (var x = 0; x < width; x++) {
  77037. var srcPos = (x + y * width);
  77038. byteArray[index] = srcData[srcPos];
  77039. index++;
  77040. }
  77041. }
  77042. return byteArray;
  77043. };
  77044. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77045. if (lodIndex === void 0) { lodIndex = -1; }
  77046. var ext = engine.getCaps().s3tc;
  77047. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77048. var fourCC, width, height, dataLength = 0, dataOffset;
  77049. var byteArray, mipmapCount, mip;
  77050. var internalFormat = 0;
  77051. var format = 0;
  77052. var blockBytes = 1;
  77053. if (header[off_magic] !== DDS_MAGIC) {
  77054. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77055. return;
  77056. }
  77057. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77058. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77059. return;
  77060. }
  77061. if (info.isCompressed && !ext) {
  77062. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77063. return;
  77064. }
  77065. var bpp = header[off_RGBbpp];
  77066. dataOffset = header[off_size] + 4;
  77067. var computeFormats = false;
  77068. if (info.isFourCC) {
  77069. fourCC = header[off_pfFourCC];
  77070. switch (fourCC) {
  77071. case FOURCC_DXT1:
  77072. blockBytes = 8;
  77073. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77074. break;
  77075. case FOURCC_DXT3:
  77076. blockBytes = 16;
  77077. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77078. break;
  77079. case FOURCC_DXT5:
  77080. blockBytes = 16;
  77081. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77082. break;
  77083. case FOURCC_D3DFMT_R16G16B16A16F:
  77084. computeFormats = true;
  77085. break;
  77086. case FOURCC_D3DFMT_R32G32B32A32F:
  77087. computeFormats = true;
  77088. break;
  77089. case FOURCC_DX10:
  77090. // There is an additionnal header so dataOffset need to be changed
  77091. dataOffset += 5 * 4; // 5 uints
  77092. var supported = false;
  77093. switch (info.dxgiFormat) {
  77094. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77095. computeFormats = true;
  77096. supported = true;
  77097. break;
  77098. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77099. info.isRGB = true;
  77100. info.isFourCC = false;
  77101. bpp = 32;
  77102. supported = true;
  77103. break;
  77104. }
  77105. if (supported) {
  77106. break;
  77107. }
  77108. default:
  77109. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77110. return;
  77111. }
  77112. }
  77113. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77114. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77115. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77116. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77117. if (computeFormats) {
  77118. format = engine._getWebGLTextureType(info.textureType);
  77119. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77120. }
  77121. mipmapCount = 1;
  77122. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77123. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77124. }
  77125. for (var face = 0; face < faces; face++) {
  77126. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77127. width = header[off_width];
  77128. height = header[off_height];
  77129. for (mip = 0; mip < mipmapCount; ++mip) {
  77130. if (lodIndex === -1 || lodIndex === mip) {
  77131. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77132. var i = (lodIndex === -1) ? mip : 0;
  77133. if (!info.isCompressed && info.isFourCC) {
  77134. dataLength = width * height * 4;
  77135. var floatArray = null;
  77136. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77137. if (bpp === 128) {
  77138. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77139. }
  77140. else if (bpp === 64) {
  77141. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77142. }
  77143. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77144. format = engine._getWebGLTextureType(info.textureType);
  77145. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77146. }
  77147. else {
  77148. if (bpp === 128) {
  77149. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77150. }
  77151. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77152. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77153. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77154. format = engine._getWebGLTextureType(info.textureType);
  77155. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77156. }
  77157. else {
  77158. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77159. }
  77160. }
  77161. if (floatArray) {
  77162. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77163. }
  77164. }
  77165. else if (info.isRGB) {
  77166. if (bpp === 24) {
  77167. dataLength = width * height * 3;
  77168. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77169. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77170. }
  77171. else {
  77172. dataLength = width * height * 4;
  77173. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77174. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77175. }
  77176. }
  77177. else if (info.isLuminance) {
  77178. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77179. var unpaddedRowSize = width;
  77180. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77181. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77182. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77183. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77184. }
  77185. else {
  77186. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77187. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77188. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77189. }
  77190. }
  77191. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77192. width *= 0.5;
  77193. height *= 0.5;
  77194. width = Math.max(1.0, width);
  77195. height = Math.max(1.0, height);
  77196. }
  77197. if (currentFace !== undefined) {
  77198. // Loading a single face
  77199. break;
  77200. }
  77201. }
  77202. };
  77203. DDSTools.StoreLODInAlphaChannel = false;
  77204. return DDSTools;
  77205. }());
  77206. BABYLON.DDSTools = DDSTools;
  77207. })(BABYLON || (BABYLON = {}));
  77208. //# sourceMappingURL=babylon.dds.js.map
  77209. var BABYLON;
  77210. (function (BABYLON) {
  77211. /**
  77212. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77213. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77214. */
  77215. var KhronosTextureContainer = /** @class */ (function () {
  77216. /**
  77217. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77218. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77219. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77220. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77221. */
  77222. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77223. this.arrayBuffer = arrayBuffer;
  77224. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77225. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77226. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77227. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77228. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77229. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77230. BABYLON.Tools.Error("texture missing KTX identifier");
  77231. return;
  77232. }
  77233. // load the reset of the header in native 32 bit int
  77234. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77235. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77236. var oppositeEndianess = header[0] === 0x01020304;
  77237. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77238. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77239. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77240. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77241. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77242. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77243. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77244. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77245. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77246. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77247. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77248. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77249. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77250. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77251. if (this.glType !== 0) {
  77252. BABYLON.Tools.Error("only compressed formats currently supported");
  77253. return;
  77254. }
  77255. else {
  77256. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77257. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77258. }
  77259. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77260. BABYLON.Tools.Error("only 2D textures currently supported");
  77261. return;
  77262. }
  77263. if (this.numberOfArrayElements !== 0) {
  77264. BABYLON.Tools.Error("texture arrays not currently supported");
  77265. return;
  77266. }
  77267. if (this.numberOfFaces !== facesExpected) {
  77268. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77269. return;
  77270. }
  77271. // we now have a completely validated file, so could use existence of loadType as success
  77272. // would need to make this more elaborate & adjust checks above to support more than one load type
  77273. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77274. }
  77275. // not as fast hardware based, but will probably never need to use
  77276. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77277. return ((val & 0xFF) << 24)
  77278. | ((val & 0xFF00) << 8)
  77279. | ((val >> 8) & 0xFF00)
  77280. | ((val >> 24) & 0xFF);
  77281. };
  77282. /**
  77283. * It is assumed that the texture has already been created & is currently bound
  77284. */
  77285. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77286. switch (this.loadType) {
  77287. case KhronosTextureContainer.COMPRESSED_2D:
  77288. this._upload2DCompressedLevels(gl, loadMipmaps);
  77289. break;
  77290. case KhronosTextureContainer.TEX_2D:
  77291. case KhronosTextureContainer.COMPRESSED_3D:
  77292. case KhronosTextureContainer.TEX_3D:
  77293. }
  77294. };
  77295. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77296. // initialize width & height for level 1
  77297. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77298. var width = this.pixelWidth;
  77299. var height = this.pixelHeight;
  77300. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77301. for (var level = 0; level < mipmapCount; level++) {
  77302. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77303. for (var face = 0; face < this.numberOfFaces; face++) {
  77304. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77305. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77306. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77307. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77308. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77309. }
  77310. width = Math.max(1.0, width * 0.5);
  77311. height = Math.max(1.0, height * 0.5);
  77312. }
  77313. };
  77314. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77315. // load types
  77316. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77317. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77318. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77319. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77320. return KhronosTextureContainer;
  77321. }());
  77322. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77323. })(BABYLON || (BABYLON = {}));
  77324. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77325. var BABYLON;
  77326. (function (BABYLON) {
  77327. var Debug = /** @class */ (function () {
  77328. function Debug() {
  77329. }
  77330. Debug.AxesViewer = /** @class */ (function () {
  77331. function AxesViewer(scene, scaleLines) {
  77332. if (scaleLines === void 0) { scaleLines = 1; }
  77333. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77334. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77335. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77336. this.scaleLines = 1;
  77337. this.scaleLines = scaleLines;
  77338. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77339. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77340. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77341. this._xmesh.renderingGroupId = 2;
  77342. this._ymesh.renderingGroupId = 2;
  77343. this._zmesh.renderingGroupId = 2;
  77344. this._xmesh.material.checkReadyOnlyOnce = true;
  77345. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77346. this._ymesh.material.checkReadyOnlyOnce = true;
  77347. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77348. this._zmesh.material.checkReadyOnlyOnce = true;
  77349. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77350. this.scene = scene;
  77351. }
  77352. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77353. var scaleLines = this.scaleLines;
  77354. if (this._xmesh) {
  77355. this._xmesh.position.copyFrom(position);
  77356. }
  77357. if (this._ymesh) {
  77358. this._ymesh.position.copyFrom(position);
  77359. }
  77360. if (this._zmesh) {
  77361. this._zmesh.position.copyFrom(position);
  77362. }
  77363. var point2 = this._xline[1];
  77364. point2.x = xaxis.x * scaleLines;
  77365. point2.y = xaxis.y * scaleLines;
  77366. point2.z = xaxis.z * scaleLines;
  77367. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77368. point2 = this._yline[1];
  77369. point2.x = yaxis.x * scaleLines;
  77370. point2.y = yaxis.y * scaleLines;
  77371. point2.z = yaxis.z * scaleLines;
  77372. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77373. point2 = this._zline[1];
  77374. point2.x = zaxis.x * scaleLines;
  77375. point2.y = zaxis.y * scaleLines;
  77376. point2.z = zaxis.z * scaleLines;
  77377. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77378. };
  77379. AxesViewer.prototype.dispose = function () {
  77380. if (this._xmesh) {
  77381. this._xmesh.dispose();
  77382. }
  77383. if (this._ymesh) {
  77384. this._ymesh.dispose();
  77385. }
  77386. if (this._zmesh) {
  77387. this._zmesh.dispose();
  77388. }
  77389. this._xmesh = null;
  77390. this._ymesh = null;
  77391. this._zmesh = null;
  77392. this.scene = null;
  77393. };
  77394. return AxesViewer;
  77395. }());
  77396. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77397. __extends(BoneAxesViewer, _super);
  77398. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77399. if (scaleLines === void 0) { scaleLines = 1; }
  77400. var _this = _super.call(this, scene, scaleLines) || this;
  77401. _this.pos = BABYLON.Vector3.Zero();
  77402. _this.xaxis = BABYLON.Vector3.Zero();
  77403. _this.yaxis = BABYLON.Vector3.Zero();
  77404. _this.zaxis = BABYLON.Vector3.Zero();
  77405. _this.mesh = mesh;
  77406. _this.bone = bone;
  77407. return _this;
  77408. }
  77409. BoneAxesViewer.prototype.update = function () {
  77410. if (!this.mesh || !this.bone) {
  77411. return;
  77412. }
  77413. var bone = this.bone;
  77414. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77415. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77416. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77417. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77418. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77419. };
  77420. BoneAxesViewer.prototype.dispose = function () {
  77421. if (this.mesh) {
  77422. this.mesh = null;
  77423. this.bone = null;
  77424. _super.prototype.dispose.call(this);
  77425. }
  77426. };
  77427. return BoneAxesViewer;
  77428. }(Debug.AxesViewer));
  77429. Debug.PhysicsViewer = /** @class */ (function () {
  77430. function PhysicsViewer(scene) {
  77431. this._impostors = [];
  77432. this._meshes = [];
  77433. this._numMeshes = 0;
  77434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77435. var physicEngine = this._scene.getPhysicsEngine();
  77436. if (physicEngine) {
  77437. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77438. }
  77439. }
  77440. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77441. var plugin = this._physicsEnginePlugin;
  77442. for (var i = 0; i < this._numMeshes; i++) {
  77443. var impostor = this._impostors[i];
  77444. if (!impostor) {
  77445. continue;
  77446. }
  77447. if (impostor.isDisposed) {
  77448. this.hideImpostor(this._impostors[i--]);
  77449. }
  77450. else {
  77451. var mesh = this._meshes[i];
  77452. if (mesh && plugin) {
  77453. plugin.syncMeshWithImpostor(mesh, impostor);
  77454. }
  77455. }
  77456. }
  77457. };
  77458. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77459. if (!this._scene) {
  77460. return;
  77461. }
  77462. for (var i = 0; i < this._numMeshes; i++) {
  77463. if (this._impostors[i] == impostor) {
  77464. return;
  77465. }
  77466. }
  77467. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77468. if (debugMesh) {
  77469. this._impostors[this._numMeshes] = impostor;
  77470. this._meshes[this._numMeshes] = debugMesh;
  77471. if (this._numMeshes === 0) {
  77472. this._renderFunction = this._updateDebugMeshes.bind(this);
  77473. this._scene.registerBeforeRender(this._renderFunction);
  77474. }
  77475. this._numMeshes++;
  77476. }
  77477. };
  77478. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77479. if (!impostor || !this._scene) {
  77480. return;
  77481. }
  77482. var removed = false;
  77483. for (var i = 0; i < this._numMeshes; i++) {
  77484. if (this._impostors[i] == impostor) {
  77485. var mesh = this._meshes[i];
  77486. if (!mesh) {
  77487. continue;
  77488. }
  77489. this._scene.removeMesh(mesh);
  77490. mesh.dispose();
  77491. this._numMeshes--;
  77492. if (this._numMeshes > 0) {
  77493. this._meshes[i] = this._meshes[this._numMeshes];
  77494. this._impostors[i] = this._impostors[this._numMeshes];
  77495. this._meshes[this._numMeshes] = null;
  77496. this._impostors[this._numMeshes] = null;
  77497. }
  77498. else {
  77499. this._meshes[0] = null;
  77500. this._impostors[0] = null;
  77501. }
  77502. removed = true;
  77503. break;
  77504. }
  77505. }
  77506. if (removed && this._numMeshes === 0) {
  77507. this._scene.unregisterBeforeRender(this._renderFunction);
  77508. }
  77509. };
  77510. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77511. if (!this._debugMaterial) {
  77512. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77513. this._debugMaterial.wireframe = true;
  77514. }
  77515. return this._debugMaterial;
  77516. };
  77517. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77518. if (!this._debugBoxMesh) {
  77519. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77520. this._debugBoxMesh.renderingGroupId = 1;
  77521. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77522. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77523. scene.removeMesh(this._debugBoxMesh);
  77524. }
  77525. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77526. };
  77527. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77528. if (!this._debugSphereMesh) {
  77529. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77530. this._debugSphereMesh.renderingGroupId = 1;
  77531. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77532. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77533. scene.removeMesh(this._debugSphereMesh);
  77534. }
  77535. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77536. };
  77537. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77538. var mesh = null;
  77539. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77540. mesh = this._getDebugBoxMesh(scene);
  77541. impostor.getBoxSizeToRef(mesh.scaling);
  77542. }
  77543. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77544. mesh = this._getDebugSphereMesh(scene);
  77545. var radius = impostor.getRadius();
  77546. mesh.scaling.x = radius * 2;
  77547. mesh.scaling.y = radius * 2;
  77548. mesh.scaling.z = radius * 2;
  77549. }
  77550. return mesh;
  77551. };
  77552. PhysicsViewer.prototype.dispose = function () {
  77553. for (var i = 0; i < this._numMeshes; i++) {
  77554. this.hideImpostor(this._impostors[i]);
  77555. }
  77556. if (this._debugBoxMesh) {
  77557. this._debugBoxMesh.dispose();
  77558. }
  77559. if (this._debugSphereMesh) {
  77560. this._debugSphereMesh.dispose();
  77561. }
  77562. if (this._debugMaterial) {
  77563. this._debugMaterial.dispose();
  77564. }
  77565. this._impostors.length = 0;
  77566. this._scene = null;
  77567. this._physicsEnginePlugin = null;
  77568. };
  77569. return PhysicsViewer;
  77570. }());
  77571. Debug.SkeletonViewer = /** @class */ (function () {
  77572. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77573. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77574. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77575. this.skeleton = skeleton;
  77576. this.mesh = mesh;
  77577. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77578. this.renderingGroupId = renderingGroupId;
  77579. this.color = BABYLON.Color3.White();
  77580. this._debugLines = new Array();
  77581. this._isEnabled = false;
  77582. this._scene = scene;
  77583. this.update();
  77584. this._renderFunction = this.update.bind(this);
  77585. }
  77586. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77587. get: function () {
  77588. return this._isEnabled;
  77589. },
  77590. set: function (value) {
  77591. if (this._isEnabled === value) {
  77592. return;
  77593. }
  77594. this._isEnabled = value;
  77595. if (value) {
  77596. this._scene.registerBeforeRender(this._renderFunction);
  77597. }
  77598. else {
  77599. this._scene.unregisterBeforeRender(this._renderFunction);
  77600. }
  77601. },
  77602. enumerable: true,
  77603. configurable: true
  77604. });
  77605. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77606. if (x === void 0) { x = 0; }
  77607. if (y === void 0) { y = 0; }
  77608. if (z === void 0) { z = 0; }
  77609. var tmat = BABYLON.Tmp.Matrix[0];
  77610. var parentBone = bone.getParent();
  77611. tmat.copyFrom(bone.getLocalMatrix());
  77612. if (x !== 0 || y !== 0 || z !== 0) {
  77613. var tmat2 = BABYLON.Tmp.Matrix[1];
  77614. BABYLON.Matrix.IdentityToRef(tmat2);
  77615. tmat2.m[12] = x;
  77616. tmat2.m[13] = y;
  77617. tmat2.m[14] = z;
  77618. tmat2.multiplyToRef(tmat, tmat);
  77619. }
  77620. if (parentBone) {
  77621. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77622. }
  77623. tmat.multiplyToRef(meshMat, tmat);
  77624. position.x = tmat.m[12];
  77625. position.y = tmat.m[13];
  77626. position.z = tmat.m[14];
  77627. };
  77628. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77629. var len = bones.length;
  77630. var meshPos = this.mesh.position;
  77631. for (var i = 0; i < len; i++) {
  77632. var bone = bones[i];
  77633. var points = this._debugLines[i];
  77634. if (!points) {
  77635. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77636. this._debugLines[i] = points;
  77637. }
  77638. this._getBonePosition(points[0], bone, meshMat);
  77639. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77640. points[0].subtractInPlace(meshPos);
  77641. points[1].subtractInPlace(meshPos);
  77642. }
  77643. };
  77644. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77645. var len = bones.length;
  77646. var boneNum = 0;
  77647. var meshPos = this.mesh.position;
  77648. for (var i = len - 1; i >= 0; i--) {
  77649. var childBone = bones[i];
  77650. var parentBone = childBone.getParent();
  77651. if (!parentBone) {
  77652. continue;
  77653. }
  77654. var points = this._debugLines[boneNum];
  77655. if (!points) {
  77656. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77657. this._debugLines[boneNum] = points;
  77658. }
  77659. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77660. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77661. points[0].subtractInPlace(meshPos);
  77662. points[1].subtractInPlace(meshPos);
  77663. boneNum++;
  77664. }
  77665. };
  77666. SkeletonViewer.prototype.update = function () {
  77667. if (this.autoUpdateBonesMatrices) {
  77668. this.skeleton.computeAbsoluteTransforms();
  77669. }
  77670. if (this.skeleton.bones[0].length === undefined) {
  77671. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77672. }
  77673. else {
  77674. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77675. }
  77676. if (!this._debugMesh) {
  77677. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77678. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77679. }
  77680. else {
  77681. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77682. }
  77683. this._debugMesh.position.copyFrom(this.mesh.position);
  77684. this._debugMesh.color = this.color;
  77685. };
  77686. SkeletonViewer.prototype.dispose = function () {
  77687. if (this._debugMesh) {
  77688. this.isEnabled = false;
  77689. this._debugMesh.dispose();
  77690. this._debugMesh = null;
  77691. }
  77692. };
  77693. return SkeletonViewer;
  77694. }());
  77695. return Debug;
  77696. }());
  77697. BABYLON.Debug = Debug;
  77698. })(BABYLON || (BABYLON = {}));
  77699. //# sourceMappingURL=babylon.debugModules.js.map
  77700. var BABYLON;
  77701. (function (BABYLON) {
  77702. var RayHelper = /** @class */ (function () {
  77703. function RayHelper(ray) {
  77704. this.ray = ray;
  77705. }
  77706. RayHelper.CreateAndShow = function (ray, scene, color) {
  77707. var helper = new RayHelper(ray);
  77708. helper.show(scene, color);
  77709. return helper;
  77710. };
  77711. RayHelper.prototype.show = function (scene, color) {
  77712. if (!this._renderFunction && this.ray) {
  77713. var ray = this.ray;
  77714. this._renderFunction = this._render.bind(this);
  77715. this._scene = scene;
  77716. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  77717. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  77718. if (this._renderFunction) {
  77719. this._scene.registerBeforeRender(this._renderFunction);
  77720. }
  77721. }
  77722. if (color && this._renderLine) {
  77723. this._renderLine.color.copyFrom(color);
  77724. }
  77725. };
  77726. RayHelper.prototype.hide = function () {
  77727. if (this._renderFunction && this._scene) {
  77728. this._scene.unregisterBeforeRender(this._renderFunction);
  77729. this._scene = null;
  77730. this._renderFunction = null;
  77731. if (this._renderLine) {
  77732. this._renderLine.dispose();
  77733. this._renderLine = null;
  77734. }
  77735. this._renderPoints = [];
  77736. }
  77737. };
  77738. RayHelper.prototype._render = function () {
  77739. var ray = this.ray;
  77740. if (!ray) {
  77741. return;
  77742. }
  77743. var point = this._renderPoints[1];
  77744. var len = Math.min(ray.length, 1000000);
  77745. point.copyFrom(ray.direction);
  77746. point.scaleInPlace(len);
  77747. point.addInPlace(ray.origin);
  77748. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  77749. };
  77750. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  77751. this._attachedToMesh = mesh;
  77752. var ray = this.ray;
  77753. if (!ray) {
  77754. return;
  77755. }
  77756. if (!ray.direction) {
  77757. ray.direction = BABYLON.Vector3.Zero();
  77758. }
  77759. if (!ray.origin) {
  77760. ray.origin = BABYLON.Vector3.Zero();
  77761. }
  77762. if (length) {
  77763. ray.length = length;
  77764. }
  77765. if (!meshSpaceOrigin) {
  77766. meshSpaceOrigin = BABYLON.Vector3.Zero();
  77767. }
  77768. if (!meshSpaceDirection) {
  77769. // -1 so that this will work with Mesh.lookAt
  77770. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  77771. }
  77772. if (!this._meshSpaceDirection) {
  77773. this._meshSpaceDirection = meshSpaceDirection.clone();
  77774. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  77775. }
  77776. else {
  77777. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  77778. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  77779. }
  77780. if (!this._updateToMeshFunction) {
  77781. this._updateToMeshFunction = this._updateToMesh.bind(this);
  77782. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  77783. }
  77784. this._updateToMesh();
  77785. };
  77786. RayHelper.prototype.detachFromMesh = function () {
  77787. if (this._attachedToMesh) {
  77788. if (this._updateToMeshFunction) {
  77789. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  77790. }
  77791. this._attachedToMesh = null;
  77792. this._updateToMeshFunction = null;
  77793. }
  77794. };
  77795. RayHelper.prototype._updateToMesh = function () {
  77796. var ray = this.ray;
  77797. if (!this._attachedToMesh || !ray) {
  77798. return;
  77799. }
  77800. if (this._attachedToMesh._isDisposed) {
  77801. this.detachFromMesh();
  77802. return;
  77803. }
  77804. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  77805. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  77806. };
  77807. RayHelper.prototype.dispose = function () {
  77808. this.hide();
  77809. this.detachFromMesh();
  77810. this.ray = null;
  77811. };
  77812. return RayHelper;
  77813. }());
  77814. BABYLON.RayHelper = RayHelper;
  77815. })(BABYLON || (BABYLON = {}));
  77816. //# sourceMappingURL=babylon.rayHelper.js.map
  77817. var BABYLON;
  77818. (function (BABYLON) {
  77819. // load the inspector using require, if not present in the global namespace.
  77820. var DebugLayer = /** @class */ (function () {
  77821. function DebugLayer(scene) {
  77822. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77823. this._scene = scene;
  77824. // load inspector using require, if it doesn't exist on the global namespace.
  77825. }
  77826. /** Creates the inspector window. */
  77827. DebugLayer.prototype._createInspector = function (config) {
  77828. if (config === void 0) { config = {}; }
  77829. var popup = config.popup || false;
  77830. var initialTab = config.initialTab || 0;
  77831. var parentElement = config.parentElement || null;
  77832. if (!this._inspector) {
  77833. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77834. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  77835. } // else nothing to do,; instance is already existing
  77836. };
  77837. DebugLayer.prototype.isVisible = function () {
  77838. if (!this._inspector) {
  77839. return false;
  77840. }
  77841. return true;
  77842. };
  77843. DebugLayer.prototype.hide = function () {
  77844. if (this._inspector) {
  77845. try {
  77846. this._inspector.dispose();
  77847. }
  77848. catch (e) {
  77849. // If the inspector has been removed directly from the inspector tool
  77850. }
  77851. this._inspector = null;
  77852. }
  77853. };
  77854. DebugLayer.prototype.show = function (config) {
  77855. if (config === void 0) { config = {}; }
  77856. if (typeof this.BJSINSPECTOR == 'undefined') {
  77857. // Load inspector and add it to the DOM
  77858. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77859. }
  77860. else {
  77861. // Otherwise creates the inspector
  77862. this._createInspector(config);
  77863. }
  77864. };
  77865. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77866. return DebugLayer;
  77867. }());
  77868. BABYLON.DebugLayer = DebugLayer;
  77869. })(BABYLON || (BABYLON = {}));
  77870. //# sourceMappingURL=babylon.debugLayer.js.map
  77871. var BABYLON;
  77872. (function (BABYLON) {
  77873. var BoundingBoxRenderer = /** @class */ (function () {
  77874. function BoundingBoxRenderer(scene) {
  77875. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77876. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77877. this.showBackLines = true;
  77878. this.renderList = new BABYLON.SmartArray(32);
  77879. this._vertexBuffers = {};
  77880. this._scene = scene;
  77881. }
  77882. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77883. if (this._colorShader) {
  77884. return;
  77885. }
  77886. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77887. attributes: [BABYLON.VertexBuffer.PositionKind],
  77888. uniforms: ["world", "viewProjection", "color"]
  77889. });
  77890. var engine = this._scene.getEngine();
  77891. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77892. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77893. this._createIndexBuffer();
  77894. };
  77895. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77896. var engine = this._scene.getEngine();
  77897. 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]);
  77898. };
  77899. BoundingBoxRenderer.prototype._rebuild = function () {
  77900. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77901. if (vb) {
  77902. vb._rebuild();
  77903. }
  77904. this._createIndexBuffer();
  77905. };
  77906. BoundingBoxRenderer.prototype.reset = function () {
  77907. this.renderList.reset();
  77908. };
  77909. BoundingBoxRenderer.prototype.render = function () {
  77910. if (this.renderList.length === 0) {
  77911. return;
  77912. }
  77913. this._prepareRessources();
  77914. if (!this._colorShader.isReady()) {
  77915. return;
  77916. }
  77917. var engine = this._scene.getEngine();
  77918. engine.setDepthWrite(false);
  77919. this._colorShader._preBind();
  77920. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77921. var boundingBox = this.renderList.data[boundingBoxIndex];
  77922. var min = boundingBox.minimum;
  77923. var max = boundingBox.maximum;
  77924. var diff = max.subtract(min);
  77925. var median = min.add(diff.scale(0.5));
  77926. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77927. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77928. .multiply(boundingBox.getWorldMatrix());
  77929. // VBOs
  77930. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77931. if (this.showBackLines) {
  77932. // Back
  77933. engine.setDepthFunctionToGreaterOrEqual();
  77934. this._scene.resetCachedMaterial();
  77935. this._colorShader.setColor4("color", this.backColor.toColor4());
  77936. this._colorShader.bind(worldMatrix);
  77937. // Draw order
  77938. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77939. }
  77940. // Front
  77941. engine.setDepthFunctionToLess();
  77942. this._scene.resetCachedMaterial();
  77943. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77944. this._colorShader.bind(worldMatrix);
  77945. // Draw order
  77946. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77947. }
  77948. this._colorShader.unbind();
  77949. engine.setDepthFunctionToLessOrEqual();
  77950. engine.setDepthWrite(true);
  77951. };
  77952. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77953. this._prepareRessources();
  77954. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77955. return;
  77956. }
  77957. var engine = this._scene.getEngine();
  77958. engine.setDepthWrite(false);
  77959. engine.setColorWrite(false);
  77960. this._colorShader._preBind();
  77961. var boundingBox = mesh._boundingInfo.boundingBox;
  77962. var min = boundingBox.minimum;
  77963. var max = boundingBox.maximum;
  77964. var diff = max.subtract(min);
  77965. var median = min.add(diff.scale(0.5));
  77966. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77967. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77968. .multiply(boundingBox.getWorldMatrix());
  77969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77970. engine.setDepthFunctionToLess();
  77971. this._scene.resetCachedMaterial();
  77972. this._colorShader.bind(worldMatrix);
  77973. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77974. this._colorShader.unbind();
  77975. engine.setDepthFunctionToLessOrEqual();
  77976. engine.setDepthWrite(true);
  77977. engine.setColorWrite(true);
  77978. };
  77979. BoundingBoxRenderer.prototype.dispose = function () {
  77980. if (!this._colorShader) {
  77981. return;
  77982. }
  77983. this.renderList.dispose();
  77984. this._colorShader.dispose();
  77985. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77986. if (buffer) {
  77987. buffer.dispose();
  77988. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77989. }
  77990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77991. };
  77992. return BoundingBoxRenderer;
  77993. }());
  77994. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77995. })(BABYLON || (BABYLON = {}));
  77996. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77997. var BABYLON;
  77998. (function (BABYLON) {
  77999. var MorphTarget = /** @class */ (function () {
  78000. function MorphTarget(name, influence) {
  78001. if (influence === void 0) { influence = 0; }
  78002. this.name = name;
  78003. this.animations = new Array();
  78004. this._positions = null;
  78005. this._normals = null;
  78006. this._tangents = null;
  78007. this.onInfluenceChanged = new BABYLON.Observable();
  78008. this.influence = influence;
  78009. }
  78010. Object.defineProperty(MorphTarget.prototype, "influence", {
  78011. get: function () {
  78012. return this._influence;
  78013. },
  78014. set: function (influence) {
  78015. if (this._influence === influence) {
  78016. return;
  78017. }
  78018. var previous = this._influence;
  78019. this._influence = influence;
  78020. if (this.onInfluenceChanged.hasObservers) {
  78021. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78022. }
  78023. },
  78024. enumerable: true,
  78025. configurable: true
  78026. });
  78027. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78028. get: function () {
  78029. return !!this._positions;
  78030. },
  78031. enumerable: true,
  78032. configurable: true
  78033. });
  78034. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78035. get: function () {
  78036. return !!this._normals;
  78037. },
  78038. enumerable: true,
  78039. configurable: true
  78040. });
  78041. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78042. get: function () {
  78043. return !!this._tangents;
  78044. },
  78045. enumerable: true,
  78046. configurable: true
  78047. });
  78048. MorphTarget.prototype.setPositions = function (data) {
  78049. this._positions = data;
  78050. };
  78051. MorphTarget.prototype.getPositions = function () {
  78052. return this._positions;
  78053. };
  78054. MorphTarget.prototype.setNormals = function (data) {
  78055. this._normals = data;
  78056. };
  78057. MorphTarget.prototype.getNormals = function () {
  78058. return this._normals;
  78059. };
  78060. MorphTarget.prototype.setTangents = function (data) {
  78061. this._tangents = data;
  78062. };
  78063. MorphTarget.prototype.getTangents = function () {
  78064. return this._tangents;
  78065. };
  78066. /**
  78067. * Serializes the current target into a Serialization object.
  78068. * Returns the serialized object.
  78069. */
  78070. MorphTarget.prototype.serialize = function () {
  78071. var serializationObject = {};
  78072. serializationObject.name = this.name;
  78073. serializationObject.influence = this.influence;
  78074. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78075. if (this.hasNormals) {
  78076. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78077. }
  78078. if (this.hasTangents) {
  78079. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78080. }
  78081. // Animations
  78082. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78083. return serializationObject;
  78084. };
  78085. // Statics
  78086. MorphTarget.Parse = function (serializationObject) {
  78087. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78088. result.setPositions(serializationObject.positions);
  78089. if (serializationObject.normals) {
  78090. result.setNormals(serializationObject.normals);
  78091. }
  78092. if (serializationObject.tangents) {
  78093. result.setTangents(serializationObject.tangents);
  78094. }
  78095. // Animations
  78096. if (serializationObject.animations) {
  78097. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78098. var parsedAnimation = serializationObject.animations[animationIndex];
  78099. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78100. }
  78101. }
  78102. return result;
  78103. };
  78104. MorphTarget.FromMesh = function (mesh, name, influence) {
  78105. if (!name) {
  78106. name = mesh.name;
  78107. }
  78108. var result = new MorphTarget(name, influence);
  78109. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78110. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78111. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78112. }
  78113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78114. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78115. }
  78116. return result;
  78117. };
  78118. return MorphTarget;
  78119. }());
  78120. BABYLON.MorphTarget = MorphTarget;
  78121. })(BABYLON || (BABYLON = {}));
  78122. //# sourceMappingURL=babylon.morphTarget.js.map
  78123. var BABYLON;
  78124. (function (BABYLON) {
  78125. var MorphTargetManager = /** @class */ (function () {
  78126. function MorphTargetManager(scene) {
  78127. if (scene === void 0) { scene = null; }
  78128. this._targets = new Array();
  78129. this._targetObservable = new Array();
  78130. this._activeTargets = new BABYLON.SmartArray(16);
  78131. this._supportsNormals = false;
  78132. this._supportsTangents = false;
  78133. this._vertexCount = 0;
  78134. this._uniqueId = 0;
  78135. this._tempInfluences = new Array();
  78136. if (!scene) {
  78137. scene = BABYLON.Engine.LastCreatedScene;
  78138. }
  78139. this._scene = scene;
  78140. if (this._scene) {
  78141. this._scene.morphTargetManagers.push(this);
  78142. this._uniqueId = this._scene.getUniqueId();
  78143. }
  78144. }
  78145. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78146. get: function () {
  78147. return this._uniqueId;
  78148. },
  78149. enumerable: true,
  78150. configurable: true
  78151. });
  78152. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78153. get: function () {
  78154. return this._vertexCount;
  78155. },
  78156. enumerable: true,
  78157. configurable: true
  78158. });
  78159. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78160. get: function () {
  78161. return this._supportsNormals;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78167. get: function () {
  78168. return this._supportsTangents;
  78169. },
  78170. enumerable: true,
  78171. configurable: true
  78172. });
  78173. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78174. get: function () {
  78175. return this._targets.length;
  78176. },
  78177. enumerable: true,
  78178. configurable: true
  78179. });
  78180. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78181. get: function () {
  78182. return this._activeTargets.length;
  78183. },
  78184. enumerable: true,
  78185. configurable: true
  78186. });
  78187. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78188. get: function () {
  78189. return this._influences;
  78190. },
  78191. enumerable: true,
  78192. configurable: true
  78193. });
  78194. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78195. return this._activeTargets.data[index];
  78196. };
  78197. MorphTargetManager.prototype.getTarget = function (index) {
  78198. return this._targets[index];
  78199. };
  78200. MorphTargetManager.prototype.addTarget = function (target) {
  78201. var _this = this;
  78202. this._targets.push(target);
  78203. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78204. _this._syncActiveTargets(needUpdate);
  78205. }));
  78206. this._syncActiveTargets(true);
  78207. };
  78208. MorphTargetManager.prototype.removeTarget = function (target) {
  78209. var index = this._targets.indexOf(target);
  78210. if (index >= 0) {
  78211. this._targets.splice(index, 1);
  78212. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78213. this._syncActiveTargets(true);
  78214. }
  78215. };
  78216. /**
  78217. * Serializes the current manager into a Serialization object.
  78218. * Returns the serialized object.
  78219. */
  78220. MorphTargetManager.prototype.serialize = function () {
  78221. var serializationObject = {};
  78222. serializationObject.id = this.uniqueId;
  78223. serializationObject.targets = [];
  78224. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78225. var target = _a[_i];
  78226. serializationObject.targets.push(target.serialize());
  78227. }
  78228. return serializationObject;
  78229. };
  78230. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78231. var influenceCount = 0;
  78232. this._activeTargets.reset();
  78233. this._supportsNormals = true;
  78234. this._supportsTangents = true;
  78235. this._vertexCount = 0;
  78236. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78237. var target = _a[_i];
  78238. this._activeTargets.push(target);
  78239. this._tempInfluences[influenceCount++] = target.influence;
  78240. var positions = target.getPositions();
  78241. if (positions) {
  78242. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78243. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78244. var vertexCount = positions.length / 3;
  78245. if (this._vertexCount === 0) {
  78246. this._vertexCount = vertexCount;
  78247. }
  78248. else if (this._vertexCount !== vertexCount) {
  78249. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78250. return;
  78251. }
  78252. }
  78253. }
  78254. if (!this._influences || this._influences.length !== influenceCount) {
  78255. this._influences = new Float32Array(influenceCount);
  78256. }
  78257. for (var index = 0; index < influenceCount; index++) {
  78258. this._influences[index] = this._tempInfluences[index];
  78259. }
  78260. if (needUpdate && this._scene) {
  78261. // Flag meshes as dirty to resync with the active targets
  78262. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78263. var mesh = _c[_b];
  78264. if (mesh.morphTargetManager === this) {
  78265. mesh._syncGeometryWithMorphTargetManager();
  78266. }
  78267. }
  78268. }
  78269. };
  78270. // Statics
  78271. MorphTargetManager.Parse = function (serializationObject, scene) {
  78272. var result = new MorphTargetManager(scene);
  78273. result._uniqueId = serializationObject.id;
  78274. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78275. var targetData = _a[_i];
  78276. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78277. }
  78278. return result;
  78279. };
  78280. return MorphTargetManager;
  78281. }());
  78282. BABYLON.MorphTargetManager = MorphTargetManager;
  78283. })(BABYLON || (BABYLON = {}));
  78284. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78285. var BABYLON;
  78286. (function (BABYLON) {
  78287. var Octree = /** @class */ (function () {
  78288. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78289. if (maxDepth === void 0) { maxDepth = 2; }
  78290. this.maxDepth = maxDepth;
  78291. this.dynamicContent = new Array();
  78292. this._maxBlockCapacity = maxBlockCapacity || 64;
  78293. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78294. this._creationFunc = creationFunc;
  78295. }
  78296. // Methods
  78297. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78298. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78299. };
  78300. Octree.prototype.addMesh = function (entry) {
  78301. for (var index = 0; index < this.blocks.length; index++) {
  78302. var block = this.blocks[index];
  78303. block.addEntry(entry);
  78304. }
  78305. };
  78306. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78307. this._selectionContent.reset();
  78308. for (var index = 0; index < this.blocks.length; index++) {
  78309. var block = this.blocks[index];
  78310. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78311. }
  78312. if (allowDuplicate) {
  78313. this._selectionContent.concat(this.dynamicContent);
  78314. }
  78315. else {
  78316. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78317. }
  78318. return this._selectionContent;
  78319. };
  78320. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78321. this._selectionContent.reset();
  78322. for (var index = 0; index < this.blocks.length; index++) {
  78323. var block = this.blocks[index];
  78324. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78325. }
  78326. if (allowDuplicate) {
  78327. this._selectionContent.concat(this.dynamicContent);
  78328. }
  78329. else {
  78330. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78331. }
  78332. return this._selectionContent;
  78333. };
  78334. Octree.prototype.intersectsRay = function (ray) {
  78335. this._selectionContent.reset();
  78336. for (var index = 0; index < this.blocks.length; index++) {
  78337. var block = this.blocks[index];
  78338. block.intersectsRay(ray, this._selectionContent);
  78339. }
  78340. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78341. return this._selectionContent;
  78342. };
  78343. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78344. target.blocks = new Array();
  78345. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78346. // Segmenting space
  78347. for (var x = 0; x < 2; x++) {
  78348. for (var y = 0; y < 2; y++) {
  78349. for (var z = 0; z < 2; z++) {
  78350. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78351. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78352. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78353. block.addEntries(entries);
  78354. target.blocks.push(block);
  78355. }
  78356. }
  78357. }
  78358. };
  78359. Octree.CreationFuncForMeshes = function (entry, block) {
  78360. var boundingInfo = entry.getBoundingInfo();
  78361. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78362. block.entries.push(entry);
  78363. }
  78364. };
  78365. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78366. var boundingInfo = entry.getBoundingInfo();
  78367. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78368. block.entries.push(entry);
  78369. }
  78370. };
  78371. return Octree;
  78372. }());
  78373. BABYLON.Octree = Octree;
  78374. })(BABYLON || (BABYLON = {}));
  78375. //# sourceMappingURL=babylon.octree.js.map
  78376. var BABYLON;
  78377. (function (BABYLON) {
  78378. var OctreeBlock = /** @class */ (function () {
  78379. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78380. this.entries = new Array();
  78381. this._boundingVectors = new Array();
  78382. this._capacity = capacity;
  78383. this._depth = depth;
  78384. this._maxDepth = maxDepth;
  78385. this._creationFunc = creationFunc;
  78386. this._minPoint = minPoint;
  78387. this._maxPoint = maxPoint;
  78388. this._boundingVectors.push(minPoint.clone());
  78389. this._boundingVectors.push(maxPoint.clone());
  78390. this._boundingVectors.push(minPoint.clone());
  78391. this._boundingVectors[2].x = maxPoint.x;
  78392. this._boundingVectors.push(minPoint.clone());
  78393. this._boundingVectors[3].y = maxPoint.y;
  78394. this._boundingVectors.push(minPoint.clone());
  78395. this._boundingVectors[4].z = maxPoint.z;
  78396. this._boundingVectors.push(maxPoint.clone());
  78397. this._boundingVectors[5].z = minPoint.z;
  78398. this._boundingVectors.push(maxPoint.clone());
  78399. this._boundingVectors[6].x = minPoint.x;
  78400. this._boundingVectors.push(maxPoint.clone());
  78401. this._boundingVectors[7].y = minPoint.y;
  78402. }
  78403. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78404. // Property
  78405. get: function () {
  78406. return this._capacity;
  78407. },
  78408. enumerable: true,
  78409. configurable: true
  78410. });
  78411. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78412. get: function () {
  78413. return this._minPoint;
  78414. },
  78415. enumerable: true,
  78416. configurable: true
  78417. });
  78418. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78419. get: function () {
  78420. return this._maxPoint;
  78421. },
  78422. enumerable: true,
  78423. configurable: true
  78424. });
  78425. // Methods
  78426. OctreeBlock.prototype.addEntry = function (entry) {
  78427. if (this.blocks) {
  78428. for (var index = 0; index < this.blocks.length; index++) {
  78429. var block = this.blocks[index];
  78430. block.addEntry(entry);
  78431. }
  78432. return;
  78433. }
  78434. this._creationFunc(entry, this);
  78435. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78436. this.createInnerBlocks();
  78437. }
  78438. };
  78439. OctreeBlock.prototype.addEntries = function (entries) {
  78440. for (var index = 0; index < entries.length; index++) {
  78441. var mesh = entries[index];
  78442. this.addEntry(mesh);
  78443. }
  78444. };
  78445. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78446. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78447. if (this.blocks) {
  78448. for (var index = 0; index < this.blocks.length; index++) {
  78449. var block = this.blocks[index];
  78450. block.select(frustumPlanes, selection, allowDuplicate);
  78451. }
  78452. return;
  78453. }
  78454. if (allowDuplicate) {
  78455. selection.concat(this.entries);
  78456. }
  78457. else {
  78458. selection.concatWithNoDuplicate(this.entries);
  78459. }
  78460. }
  78461. };
  78462. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78463. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78464. if (this.blocks) {
  78465. for (var index = 0; index < this.blocks.length; index++) {
  78466. var block = this.blocks[index];
  78467. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78468. }
  78469. return;
  78470. }
  78471. if (allowDuplicate) {
  78472. selection.concat(this.entries);
  78473. }
  78474. else {
  78475. selection.concatWithNoDuplicate(this.entries);
  78476. }
  78477. }
  78478. };
  78479. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78480. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78481. if (this.blocks) {
  78482. for (var index = 0; index < this.blocks.length; index++) {
  78483. var block = this.blocks[index];
  78484. block.intersectsRay(ray, selection);
  78485. }
  78486. return;
  78487. }
  78488. selection.concatWithNoDuplicate(this.entries);
  78489. }
  78490. };
  78491. OctreeBlock.prototype.createInnerBlocks = function () {
  78492. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78493. };
  78494. return OctreeBlock;
  78495. }());
  78496. BABYLON.OctreeBlock = OctreeBlock;
  78497. })(BABYLON || (BABYLON = {}));
  78498. //# sourceMappingURL=babylon.octreeBlock.js.map
  78499. var BABYLON;
  78500. (function (BABYLON) {
  78501. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78502. __extends(VRDistortionCorrectionPostProcess, _super);
  78503. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78504. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78505. 'LensCenter',
  78506. 'Scale',
  78507. 'ScaleIn',
  78508. 'HmdWarpParam'
  78509. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78510. _this._isRightEye = isRightEye;
  78511. _this._distortionFactors = vrMetrics.distortionK;
  78512. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78513. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78514. _this.adaptScaleToCurrentViewport = true;
  78515. _this.onSizeChangedObservable.add(function () {
  78516. _this.aspectRatio = _this.width * .5 / _this.height;
  78517. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78518. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78519. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78520. });
  78521. _this.onApplyObservable.add(function (effect) {
  78522. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78523. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78524. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78525. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78526. });
  78527. return _this;
  78528. }
  78529. return VRDistortionCorrectionPostProcess;
  78530. }(BABYLON.PostProcess));
  78531. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78532. })(BABYLON || (BABYLON = {}));
  78533. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78534. var BABYLON;
  78535. (function (BABYLON) {
  78536. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78537. __extends(AnaglyphPostProcess, _super);
  78538. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78539. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78540. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78541. _this.onApplyObservable.add(function (effect) {
  78542. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78543. });
  78544. return _this;
  78545. }
  78546. return AnaglyphPostProcess;
  78547. }(BABYLON.PostProcess));
  78548. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78549. })(BABYLON || (BABYLON = {}));
  78550. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78551. var BABYLON;
  78552. (function (BABYLON) {
  78553. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78554. __extends(StereoscopicInterlacePostProcess, _super);
  78555. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78556. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78557. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78558. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78559. _this.onSizeChangedObservable.add(function () {
  78560. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78561. });
  78562. _this.onApplyObservable.add(function (effect) {
  78563. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78564. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78565. });
  78566. return _this;
  78567. }
  78568. return StereoscopicInterlacePostProcess;
  78569. }(BABYLON.PostProcess));
  78570. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78571. })(BABYLON || (BABYLON = {}));
  78572. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78573. var BABYLON;
  78574. (function (BABYLON) {
  78575. /**
  78576. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78577. * Screen rotation is taken into account.
  78578. */
  78579. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78580. function FreeCameraDeviceOrientationInput() {
  78581. var _this = this;
  78582. this._screenOrientationAngle = 0;
  78583. this._screenQuaternion = new BABYLON.Quaternion();
  78584. this._alpha = 0;
  78585. this._beta = 0;
  78586. this._gamma = 0;
  78587. this._orientationChanged = function () {
  78588. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78589. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78590. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78591. };
  78592. this._deviceOrientation = function (evt) {
  78593. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78594. _this._beta = evt.beta !== null ? evt.beta : 0;
  78595. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78596. };
  78597. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78598. this._orientationChanged();
  78599. }
  78600. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78601. get: function () {
  78602. return this._camera;
  78603. },
  78604. set: function (camera) {
  78605. this._camera = camera;
  78606. if (this._camera != null && !this._camera.rotationQuaternion) {
  78607. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78608. }
  78609. },
  78610. enumerable: true,
  78611. configurable: true
  78612. });
  78613. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78614. window.addEventListener("orientationchange", this._orientationChanged);
  78615. window.addEventListener("deviceorientation", this._deviceOrientation);
  78616. //In certain cases, the attach control is called AFTER orientation was changed,
  78617. //So this is needed.
  78618. this._orientationChanged();
  78619. };
  78620. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78621. window.removeEventListener("orientationchange", this._orientationChanged);
  78622. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78623. };
  78624. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78625. //if no device orientation provided, don't update the rotation.
  78626. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78627. if (!this._alpha)
  78628. return;
  78629. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78630. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78631. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78632. //Mirror on XY Plane
  78633. this._camera.rotationQuaternion.z *= -1;
  78634. this._camera.rotationQuaternion.w *= -1;
  78635. };
  78636. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78637. return "FreeCameraDeviceOrientationInput";
  78638. };
  78639. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78640. return "deviceOrientation";
  78641. };
  78642. return FreeCameraDeviceOrientationInput;
  78643. }());
  78644. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78645. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78646. })(BABYLON || (BABYLON = {}));
  78647. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78648. var BABYLON;
  78649. (function (BABYLON) {
  78650. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78651. function ArcRotateCameraVRDeviceOrientationInput() {
  78652. this.alphaCorrection = 1;
  78653. this.betaCorrection = 1;
  78654. this.gammaCorrection = 1;
  78655. this._alpha = 0;
  78656. this._gamma = 0;
  78657. this._dirty = false;
  78658. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78659. }
  78660. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78661. this.camera.attachControl(element, noPreventDefault);
  78662. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78663. };
  78664. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78665. if (evt.alpha !== null) {
  78666. this._alpha = +evt.alpha | 0;
  78667. }
  78668. if (evt.gamma !== null) {
  78669. this._gamma = +evt.gamma | 0;
  78670. }
  78671. this._dirty = true;
  78672. };
  78673. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78674. if (this._dirty) {
  78675. this._dirty = false;
  78676. if (this._gamma < 0) {
  78677. this._gamma = 180 + this._gamma;
  78678. }
  78679. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78680. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78681. }
  78682. };
  78683. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78684. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78685. };
  78686. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78687. return "ArcRotateCameraVRDeviceOrientationInput";
  78688. };
  78689. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  78690. return "VRDeviceOrientation";
  78691. };
  78692. return ArcRotateCameraVRDeviceOrientationInput;
  78693. }());
  78694. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  78695. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  78696. })(BABYLON || (BABYLON = {}));
  78697. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  78698. var BABYLON;
  78699. (function (BABYLON) {
  78700. var VRCameraMetrics = /** @class */ (function () {
  78701. function VRCameraMetrics() {
  78702. this.compensateDistortion = true;
  78703. }
  78704. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  78705. get: function () {
  78706. return this.hResolution / (2 * this.vResolution);
  78707. },
  78708. enumerable: true,
  78709. configurable: true
  78710. });
  78711. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  78712. get: function () {
  78713. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  78714. },
  78715. enumerable: true,
  78716. configurable: true
  78717. });
  78718. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  78719. get: function () {
  78720. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78721. var h = (4 * meters) / this.hScreenSize;
  78722. return BABYLON.Matrix.Translation(h, 0, 0);
  78723. },
  78724. enumerable: true,
  78725. configurable: true
  78726. });
  78727. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  78728. get: function () {
  78729. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78730. var h = (4 * meters) / this.hScreenSize;
  78731. return BABYLON.Matrix.Translation(-h, 0, 0);
  78732. },
  78733. enumerable: true,
  78734. configurable: true
  78735. });
  78736. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  78737. get: function () {
  78738. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  78739. },
  78740. enumerable: true,
  78741. configurable: true
  78742. });
  78743. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  78744. get: function () {
  78745. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  78746. },
  78747. enumerable: true,
  78748. configurable: true
  78749. });
  78750. VRCameraMetrics.GetDefault = function () {
  78751. var result = new VRCameraMetrics();
  78752. result.hResolution = 1280;
  78753. result.vResolution = 800;
  78754. result.hScreenSize = 0.149759993;
  78755. result.vScreenSize = 0.0935999975;
  78756. result.vScreenCenter = 0.0467999987;
  78757. result.eyeToScreenDistance = 0.0410000011;
  78758. result.lensSeparationDistance = 0.0635000020;
  78759. result.interpupillaryDistance = 0.0640000030;
  78760. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  78761. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  78762. result.postProcessScaleFactor = 1.714605507808412;
  78763. result.lensCenterOffset = 0.151976421;
  78764. return result;
  78765. };
  78766. return VRCameraMetrics;
  78767. }());
  78768. BABYLON.VRCameraMetrics = VRCameraMetrics;
  78769. })(BABYLON || (BABYLON = {}));
  78770. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  78771. var BABYLON;
  78772. (function (BABYLON) {
  78773. /**
  78774. * This represents a WebVR camera.
  78775. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  78776. * @example http://doc.babylonjs.com/how_to/webvr_camera
  78777. */
  78778. var WebVRFreeCamera = /** @class */ (function (_super) {
  78779. __extends(WebVRFreeCamera, _super);
  78780. /**
  78781. * Instantiates a WebVRFreeCamera.
  78782. * @param name The name of the WebVRFreeCamera
  78783. * @param position The starting anchor position for the camera
  78784. * @param scene The scene the camera belongs to
  78785. * @param webVROptions a set of customizable options for the webVRCamera
  78786. */
  78787. function WebVRFreeCamera(name, position, scene, webVROptions) {
  78788. if (webVROptions === void 0) { webVROptions = {}; }
  78789. var _this = _super.call(this, name, position, scene) || this;
  78790. _this.webVROptions = webVROptions;
  78791. /**
  78792. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  78793. */
  78794. _this._vrDevice = null;
  78795. /**
  78796. * The rawPose of the vrDevice.
  78797. */
  78798. _this.rawPose = null;
  78799. _this._specsVersion = "1.1";
  78800. _this._attached = false;
  78801. _this._descendants = [];
  78802. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78803. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78804. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  78805. _this._standingMatrix = null;
  78806. /**
  78807. * Represents device position in babylon space.
  78808. */
  78809. _this.devicePosition = BABYLON.Vector3.Zero();
  78810. /**
  78811. * Represents device rotation in babylon space.
  78812. */
  78813. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  78814. /**
  78815. * The scale of the device to be used when translating from device space to babylon space.
  78816. */
  78817. _this.deviceScaleFactor = 1;
  78818. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78819. _this._worldToDevice = BABYLON.Matrix.Identity();
  78820. /**
  78821. * References to the webVR controllers for the vrDevice.
  78822. */
  78823. _this.controllers = [];
  78824. /**
  78825. * Emits an event when a controller is attached.
  78826. */
  78827. _this.onControllersAttachedObservable = new BABYLON.Observable();
  78828. /**
  78829. * Emits an event when a controller's mesh has been loaded;
  78830. */
  78831. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78832. /**
  78833. * If the rig cameras be used as parent instead of this camera.
  78834. */
  78835. _this.rigParenting = true;
  78836. _this._defaultHeight = undefined;
  78837. _this._workingVector = BABYLON.Vector3.Zero();
  78838. _this._oneVector = BABYLON.Vector3.One();
  78839. _this._workingMatrix = BABYLON.Matrix.Identity();
  78840. _this._cache.position = BABYLON.Vector3.Zero();
  78841. if (webVROptions.defaultHeight) {
  78842. _this._defaultHeight = webVROptions.defaultHeight;
  78843. _this.position.y = _this._defaultHeight;
  78844. }
  78845. _this.minZ = 0.1;
  78846. //legacy support - the compensation boolean was removed.
  78847. if (arguments.length === 5) {
  78848. _this.webVROptions = arguments[4];
  78849. }
  78850. // default webVR options
  78851. if (_this.webVROptions.trackPosition == undefined) {
  78852. _this.webVROptions.trackPosition = true;
  78853. }
  78854. if (_this.webVROptions.controllerMeshes == undefined) {
  78855. _this.webVROptions.controllerMeshes = true;
  78856. }
  78857. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78858. _this.webVROptions.defaultLightingOnControllers = true;
  78859. }
  78860. _this.rotationQuaternion = new BABYLON.Quaternion();
  78861. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78862. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78863. }
  78864. //enable VR
  78865. var engine = _this.getEngine();
  78866. _this._onVREnabled = function (success) { if (success) {
  78867. _this.initControllers();
  78868. } };
  78869. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78870. engine.initWebVR().add(function (event) {
  78871. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78872. return;
  78873. }
  78874. _this._vrDevice = event.vrDisplay;
  78875. //reset the rig parameters.
  78876. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78877. if (_this._attached) {
  78878. _this.getEngine().enableVR();
  78879. }
  78880. });
  78881. if (typeof (VRFrameData) !== "undefined")
  78882. _this._frameData = new VRFrameData();
  78883. /**
  78884. * The idea behind the following lines:
  78885. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78886. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78887. * the second will not show it correctly.
  78888. *
  78889. * To solve this - each object that has the camera as parent will be added to a protected array.
  78890. * When the rig camera renders, it will take this array and set all of those to be its children.
  78891. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78892. * Amazing!
  78893. */
  78894. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78895. if (camera.parent === _this && _this.rigParenting) {
  78896. _this._descendants = _this.getDescendants(true, function (n) {
  78897. // don't take the cameras or the controllers!
  78898. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78899. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78900. return !isController && !isRigCamera;
  78901. });
  78902. _this._descendants.forEach(function (node) {
  78903. node.parent = camera;
  78904. });
  78905. }
  78906. });
  78907. scene.onAfterCameraRenderObservable.add(function (camera) {
  78908. if (camera.parent === _this && _this.rigParenting) {
  78909. _this._descendants.forEach(function (node) {
  78910. node.parent = _this;
  78911. });
  78912. }
  78913. });
  78914. return _this;
  78915. }
  78916. /**
  78917. * Gets the device distance from the ground in meters.
  78918. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  78919. */
  78920. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78921. if (this._standingMatrix) {
  78922. // Add standing matrix offset to get real offset from ground in room
  78923. this._standingMatrix.getTranslationToRef(this._workingVector);
  78924. return this._deviceRoomPosition.y + this._workingVector.y;
  78925. }
  78926. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78927. return this._defaultHeight || 0;
  78928. };
  78929. /**
  78930. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78931. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78932. */
  78933. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78934. var _this = this;
  78935. if (callback === void 0) { callback = function (bool) { }; }
  78936. // Use standing matrix if available
  78937. this.getEngine().initWebVRAsync().then(function (result) {
  78938. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  78939. callback(false);
  78940. }
  78941. else {
  78942. _this._standingMatrix = new BABYLON.Matrix();
  78943. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78944. if (!_this.getScene().useRightHandedSystem) {
  78945. [2, 6, 8, 9, 14].forEach(function (num) {
  78946. if (_this._standingMatrix) {
  78947. _this._standingMatrix.m[num] *= -1;
  78948. }
  78949. });
  78950. }
  78951. callback(true);
  78952. }
  78953. });
  78954. };
  78955. /**
  78956. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78957. * @returns A promise with a boolean set to if the standing matrix is supported.
  78958. */
  78959. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  78960. var _this = this;
  78961. return new Promise(function (res, rej) {
  78962. _this.useStandingMatrix(function (supported) {
  78963. res(supported);
  78964. });
  78965. });
  78966. };
  78967. /**
  78968. * Disposes the camera
  78969. */
  78970. WebVRFreeCamera.prototype.dispose = function () {
  78971. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78972. _super.prototype.dispose.call(this);
  78973. };
  78974. /**
  78975. * Gets a vrController by name.
  78976. * @param name The name of the controller to retreive
  78977. * @returns the controller matching the name specified or null if not found
  78978. */
  78979. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78980. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78981. var gp = _a[_i];
  78982. if (gp.hand === name) {
  78983. return gp;
  78984. }
  78985. }
  78986. return null;
  78987. };
  78988. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78989. /**
  78990. * The controller corrisponding to the users left hand.
  78991. */
  78992. get: function () {
  78993. if (!this._leftController) {
  78994. this._leftController = this.getControllerByName("left");
  78995. }
  78996. return this._leftController;
  78997. },
  78998. enumerable: true,
  78999. configurable: true
  79000. });
  79001. ;
  79002. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79003. /**
  79004. * The controller corrisponding to the users right hand.
  79005. */
  79006. get: function () {
  79007. if (!this._rightController) {
  79008. this._rightController = this.getControllerByName("right");
  79009. }
  79010. return this._rightController;
  79011. },
  79012. enumerable: true,
  79013. configurable: true
  79014. });
  79015. ;
  79016. /**
  79017. * Casts a ray forward from the vrCamera's gaze.
  79018. * @param length Length of the ray (default: 100)
  79019. * @returns the ray corrisponding to the gaze
  79020. */
  79021. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79022. if (length === void 0) { length = 100; }
  79023. if (this.leftCamera) {
  79024. // Use left eye to avoid computation to compute center on every call
  79025. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79026. }
  79027. else {
  79028. return _super.prototype.getForwardRay.call(this, length);
  79029. }
  79030. };
  79031. /**
  79032. * Updates the camera based on device's frame data
  79033. */
  79034. WebVRFreeCamera.prototype._checkInputs = function () {
  79035. if (this._vrDevice && this._vrDevice.isPresenting) {
  79036. this._vrDevice.getFrameData(this._frameData);
  79037. this.updateFromDevice(this._frameData.pose);
  79038. }
  79039. _super.prototype._checkInputs.call(this);
  79040. };
  79041. /**
  79042. * Updates the poseControlled values based on the input device pose.
  79043. * @param poseData Pose coming from the device
  79044. */
  79045. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79046. if (poseData && poseData.orientation) {
  79047. this.rawPose = poseData;
  79048. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79049. if (this.getScene().useRightHandedSystem) {
  79050. this._deviceRoomRotationQuaternion.z *= -1;
  79051. this._deviceRoomRotationQuaternion.w *= -1;
  79052. }
  79053. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79054. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79055. if (this.getScene().useRightHandedSystem) {
  79056. this._deviceRoomPosition.z *= -1;
  79057. }
  79058. }
  79059. }
  79060. };
  79061. /**
  79062. * WebVR's attach control will start broadcasting frames to the device.
  79063. * Note that in certain browsers (chrome for example) this function must be called
  79064. * within a user-interaction callback. Example:
  79065. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79066. *
  79067. * @param element html element to attach the vrDevice to
  79068. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79069. */
  79070. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79071. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79072. this._attached = true;
  79073. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79074. if (this._vrDevice) {
  79075. this.getEngine().enableVR();
  79076. }
  79077. };
  79078. /**
  79079. * Detaches the camera from the html element and disables VR
  79080. *
  79081. * @param element html element to detach from
  79082. */
  79083. WebVRFreeCamera.prototype.detachControl = function (element) {
  79084. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79085. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79086. _super.prototype.detachControl.call(this, element);
  79087. this._attached = false;
  79088. this.getEngine().disableVR();
  79089. };
  79090. /**
  79091. * @returns the name of this class
  79092. */
  79093. WebVRFreeCamera.prototype.getClassName = function () {
  79094. return "WebVRFreeCamera";
  79095. };
  79096. /**
  79097. * Calls resetPose on the vrDisplay
  79098. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79099. */
  79100. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79101. //uses the vrDisplay's "resetPose()".
  79102. //pitch and roll won't be affected.
  79103. this._vrDevice.resetPose();
  79104. };
  79105. /**
  79106. * Updates the rig cameras (left and right eye)
  79107. */
  79108. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79109. var camLeft = this._rigCameras[0];
  79110. var camRight = this._rigCameras[1];
  79111. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79112. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79113. camLeft.position.copyFrom(this._deviceRoomPosition);
  79114. camRight.position.copyFrom(this._deviceRoomPosition);
  79115. };
  79116. /**
  79117. * Updates the cached values of the camera
  79118. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79119. */
  79120. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79121. var _this = this;
  79122. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79123. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79124. if (!this.updateCacheCalled) {
  79125. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79126. this.updateCacheCalled = true;
  79127. this.update();
  79128. }
  79129. // Set working vector to the device position in room space rotated by the new rotation
  79130. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79131. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79132. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79133. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79134. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79135. // Add translation from anchor position
  79136. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79137. this._workingVector.addInPlace(this.position);
  79138. this._workingVector.subtractInPlace(this._cache.position);
  79139. this._deviceToWorld.setTranslation(this._workingVector);
  79140. // Set an inverted matrix to be used when updating the camera
  79141. this._deviceToWorld.invertToRef(this._worldToDevice);
  79142. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79143. this.controllers.forEach(function (controller) {
  79144. controller._deviceToWorld = _this._deviceToWorld;
  79145. controller.update();
  79146. });
  79147. }
  79148. if (!ignoreParentClass) {
  79149. _super.prototype._updateCache.call(this);
  79150. }
  79151. this.updateCacheCalled = false;
  79152. };
  79153. /**
  79154. * Updates the current device position and rotation in the babylon world
  79155. */
  79156. WebVRFreeCamera.prototype.update = function () {
  79157. // Get current device position in babylon world
  79158. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79159. // Get current device rotation in babylon world
  79160. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79161. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79162. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79163. _super.prototype.update.call(this);
  79164. };
  79165. /**
  79166. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79167. * @returns an identity matrix
  79168. */
  79169. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79170. return BABYLON.Matrix.Identity();
  79171. };
  79172. /**
  79173. * This function is called by the two RIG cameras.
  79174. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79175. */
  79176. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79177. var _this = this;
  79178. //WebVR 1.1
  79179. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79180. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79181. if (!this.getScene().useRightHandedSystem) {
  79182. [2, 6, 8, 9, 14].forEach(function (num) {
  79183. _this._webvrViewMatrix.m[num] *= -1;
  79184. });
  79185. }
  79186. // update the camera rotation matrix
  79187. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79188. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79189. // Computing target and final matrix
  79190. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79191. var parentCamera = this._cameraRigParams["parentCamera"];
  79192. // should the view matrix be updated with scale and position offset?
  79193. if (parentCamera.deviceScaleFactor !== 1) {
  79194. this._webvrViewMatrix.invert();
  79195. // scale the position, if set
  79196. if (parentCamera.deviceScaleFactor) {
  79197. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79198. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79199. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79200. }
  79201. this._webvrViewMatrix.invert();
  79202. }
  79203. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79204. return this._webvrViewMatrix;
  79205. };
  79206. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79207. var _this = this;
  79208. var parentCamera = this.parent;
  79209. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79210. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79211. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79212. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79213. //babylon compatible matrix
  79214. if (!this.getScene().useRightHandedSystem) {
  79215. [8, 9, 10, 11].forEach(function (num) {
  79216. _this._projectionMatrix.m[num] *= -1;
  79217. });
  79218. }
  79219. return this._projectionMatrix;
  79220. };
  79221. /**
  79222. * Initializes the controllers and their meshes
  79223. */
  79224. WebVRFreeCamera.prototype.initControllers = function () {
  79225. var _this = this;
  79226. this.controllers = [];
  79227. var manager = this.getScene().gamepadManager;
  79228. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79229. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79230. var webVrController = gamepad;
  79231. if (webVrController.defaultModel) {
  79232. webVrController.defaultModel.setEnabled(false);
  79233. }
  79234. if (webVrController.hand === "right") {
  79235. _this._rightController = null;
  79236. }
  79237. if (webVrController.hand === "left") {
  79238. _this._rightController = null;
  79239. }
  79240. var controllerIndex = _this.controllers.indexOf(webVrController);
  79241. if (controllerIndex !== -1) {
  79242. _this.controllers.splice(controllerIndex, 1);
  79243. }
  79244. }
  79245. });
  79246. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79247. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79248. var webVrController_1 = gamepad;
  79249. webVrController_1._deviceToWorld = _this._deviceToWorld;
  79250. if (_this.webVROptions.controllerMeshes) {
  79251. if (webVrController_1.defaultModel) {
  79252. webVrController_1.defaultModel.setEnabled(true);
  79253. }
  79254. else {
  79255. // Load the meshes
  79256. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79257. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79258. if (_this.webVROptions.defaultLightingOnControllers) {
  79259. if (!_this._lightOnControllers) {
  79260. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79261. }
  79262. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79263. var children = mesh.getChildren();
  79264. if (children.length !== 0) {
  79265. children.forEach(function (mesh) {
  79266. light.includedOnlyMeshes.push(mesh);
  79267. activateLightOnSubMeshes_1(mesh, light);
  79268. });
  79269. }
  79270. };
  79271. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79272. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79273. }
  79274. });
  79275. }
  79276. }
  79277. webVrController_1.attachToPoseControlledCamera(_this);
  79278. // since this is async - sanity check. Is the controller already stored?
  79279. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79280. //add to the controllers array
  79281. _this.controllers.push(webVrController_1);
  79282. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79283. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79284. // So we're overriding setting left & right manually to be sure
  79285. var firstViveWandDetected = false;
  79286. for (var i = 0; i < _this.controllers.length; i++) {
  79287. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79288. if (!firstViveWandDetected) {
  79289. firstViveWandDetected = true;
  79290. _this.controllers[i].hand = "left";
  79291. }
  79292. else {
  79293. _this.controllers[i].hand = "right";
  79294. }
  79295. }
  79296. }
  79297. //did we find enough controllers? Great! let the developer know.
  79298. if (_this.controllers.length >= 2) {
  79299. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79300. }
  79301. }
  79302. }
  79303. });
  79304. };
  79305. return WebVRFreeCamera;
  79306. }(BABYLON.FreeCamera));
  79307. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79308. })(BABYLON || (BABYLON = {}));
  79309. //# sourceMappingURL=babylon.webVRCamera.js.map
  79310. var BABYLON;
  79311. (function (BABYLON) {
  79312. // We're mainly based on the logic defined into the FreeCamera code
  79313. /**
  79314. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79315. * being tilted forward or back and left or right.
  79316. */
  79317. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79318. __extends(DeviceOrientationCamera, _super);
  79319. /**
  79320. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79321. * @param name The name of the camera
  79322. * @param position The start position camera
  79323. * @param scene The scene the camera belongs to
  79324. */
  79325. function DeviceOrientationCamera(name, position, scene) {
  79326. var _this = _super.call(this, name, position, scene) || this;
  79327. _this._quaternionCache = new BABYLON.Quaternion();
  79328. _this.inputs.addDeviceOrientation();
  79329. return _this;
  79330. }
  79331. /**
  79332. * Gets the current instance class name ("DeviceOrientationCamera").
  79333. * This helps avoiding instanceof at run time.
  79334. * @returns the class name
  79335. */
  79336. DeviceOrientationCamera.prototype.getClassName = function () {
  79337. return "DeviceOrientationCamera";
  79338. };
  79339. /**
  79340. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79341. */
  79342. DeviceOrientationCamera.prototype._checkInputs = function () {
  79343. _super.prototype._checkInputs.call(this);
  79344. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79345. if (this._initialQuaternion) {
  79346. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79347. }
  79348. };
  79349. /**
  79350. * Reset the camera to its default orientation on the specified axis only.
  79351. * @param axis The axis to reset
  79352. */
  79353. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79354. var _this = this;
  79355. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79356. //can only work if this camera has a rotation quaternion already.
  79357. if (!this.rotationQuaternion)
  79358. return;
  79359. if (!this._initialQuaternion) {
  79360. this._initialQuaternion = new BABYLON.Quaternion();
  79361. }
  79362. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79363. ['x', 'y', 'z'].forEach(function (axisName) {
  79364. if (!axis[axisName]) {
  79365. _this._initialQuaternion[axisName] = 0;
  79366. }
  79367. else {
  79368. _this._initialQuaternion[axisName] *= -1;
  79369. }
  79370. });
  79371. this._initialQuaternion.normalize();
  79372. //force rotation update
  79373. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79374. };
  79375. return DeviceOrientationCamera;
  79376. }(BABYLON.FreeCamera));
  79377. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79378. })(BABYLON || (BABYLON = {}));
  79379. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79380. var BABYLON;
  79381. (function (BABYLON) {
  79382. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79383. __extends(VRDeviceOrientationFreeCamera, _super);
  79384. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79385. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79386. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79387. var _this = _super.call(this, name, position, scene) || this;
  79388. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79389. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79390. return _this;
  79391. }
  79392. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79393. return "VRDeviceOrientationFreeCamera";
  79394. };
  79395. return VRDeviceOrientationFreeCamera;
  79396. }(BABYLON.DeviceOrientationCamera));
  79397. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79398. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79399. __extends(VRDeviceOrientationGamepadCamera, _super);
  79400. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79401. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79402. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79403. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79404. _this.inputs.addGamepad();
  79405. return _this;
  79406. }
  79407. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79408. return "VRDeviceOrientationGamepadCamera";
  79409. };
  79410. return VRDeviceOrientationGamepadCamera;
  79411. }(VRDeviceOrientationFreeCamera));
  79412. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79413. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79414. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79415. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79416. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79417. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79418. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79419. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79420. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79421. _this.inputs.addVRDeviceOrientation();
  79422. return _this;
  79423. }
  79424. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79425. return "VRDeviceOrientationArcRotateCamera";
  79426. };
  79427. return VRDeviceOrientationArcRotateCamera;
  79428. }(BABYLON.ArcRotateCamera));
  79429. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79430. })(BABYLON || (BABYLON = {}));
  79431. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79432. var BABYLON;
  79433. (function (BABYLON) {
  79434. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79435. __extends(AnaglyphFreeCamera, _super);
  79436. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79437. var _this = _super.call(this, name, position, scene) || this;
  79438. _this.interaxialDistance = interaxialDistance;
  79439. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79440. return _this;
  79441. }
  79442. AnaglyphFreeCamera.prototype.getClassName = function () {
  79443. return "AnaglyphFreeCamera";
  79444. };
  79445. return AnaglyphFreeCamera;
  79446. }(BABYLON.FreeCamera));
  79447. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79448. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79449. __extends(AnaglyphArcRotateCamera, _super);
  79450. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79451. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79452. _this.interaxialDistance = interaxialDistance;
  79453. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79454. return _this;
  79455. }
  79456. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79457. return "AnaglyphArcRotateCamera";
  79458. };
  79459. return AnaglyphArcRotateCamera;
  79460. }(BABYLON.ArcRotateCamera));
  79461. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79462. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79463. __extends(AnaglyphGamepadCamera, _super);
  79464. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79465. var _this = _super.call(this, name, position, scene) || this;
  79466. _this.interaxialDistance = interaxialDistance;
  79467. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79468. return _this;
  79469. }
  79470. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79471. return "AnaglyphGamepadCamera";
  79472. };
  79473. return AnaglyphGamepadCamera;
  79474. }(BABYLON.GamepadCamera));
  79475. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79476. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79477. __extends(AnaglyphUniversalCamera, _super);
  79478. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79479. var _this = _super.call(this, name, position, scene) || this;
  79480. _this.interaxialDistance = interaxialDistance;
  79481. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79482. return _this;
  79483. }
  79484. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79485. return "AnaglyphUniversalCamera";
  79486. };
  79487. return AnaglyphUniversalCamera;
  79488. }(BABYLON.UniversalCamera));
  79489. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79490. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79491. __extends(StereoscopicFreeCamera, _super);
  79492. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79493. var _this = _super.call(this, name, position, scene) || this;
  79494. _this.interaxialDistance = interaxialDistance;
  79495. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79496. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79497. return _this;
  79498. }
  79499. StereoscopicFreeCamera.prototype.getClassName = function () {
  79500. return "StereoscopicFreeCamera";
  79501. };
  79502. return StereoscopicFreeCamera;
  79503. }(BABYLON.FreeCamera));
  79504. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79505. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79506. __extends(StereoscopicArcRotateCamera, _super);
  79507. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79508. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79509. _this.interaxialDistance = interaxialDistance;
  79510. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79511. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79512. return _this;
  79513. }
  79514. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79515. return "StereoscopicArcRotateCamera";
  79516. };
  79517. return StereoscopicArcRotateCamera;
  79518. }(BABYLON.ArcRotateCamera));
  79519. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79520. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79521. __extends(StereoscopicGamepadCamera, _super);
  79522. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79523. var _this = _super.call(this, name, position, scene) || this;
  79524. _this.interaxialDistance = interaxialDistance;
  79525. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79526. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79527. return _this;
  79528. }
  79529. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79530. return "StereoscopicGamepadCamera";
  79531. };
  79532. return StereoscopicGamepadCamera;
  79533. }(BABYLON.GamepadCamera));
  79534. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79535. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79536. __extends(StereoscopicUniversalCamera, _super);
  79537. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79538. var _this = _super.call(this, name, position, scene) || this;
  79539. _this.interaxialDistance = interaxialDistance;
  79540. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79541. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79542. return _this;
  79543. }
  79544. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79545. return "StereoscopicUniversalCamera";
  79546. };
  79547. return StereoscopicUniversalCamera;
  79548. }(BABYLON.UniversalCamera));
  79549. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79550. })(BABYLON || (BABYLON = {}));
  79551. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79552. var BABYLON;
  79553. (function (BABYLON) {
  79554. var VRExperienceHelperGazer = /** @class */ (function () {
  79555. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  79556. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  79557. this.scene = scene;
  79558. this._pointerDownOnMeshAsked = false;
  79559. this._isActionableMesh = false;
  79560. this._teleportationRequestInitiated = false;
  79561. this._teleportationBackRequestInitiated = false;
  79562. this._dpadPressed = true;
  79563. this._activePointer = false;
  79564. this._id = VRExperienceHelperGazer._idCounter++;
  79565. // Gaze tracker
  79566. if (!gazeTrackerToClone) {
  79567. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  79568. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79569. this._gazeTracker.isPickable = false;
  79570. this._gazeTracker.isVisible = false;
  79571. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  79572. targetMat.specularColor = BABYLON.Color3.Black();
  79573. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79574. targetMat.backFaceCulling = false;
  79575. this._gazeTracker.material = targetMat;
  79576. }
  79577. else {
  79578. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  79579. }
  79580. }
  79581. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  79582. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  79583. };
  79584. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  79585. this._pointerDownOnMeshAsked = true;
  79586. if (this._currentMeshSelected && this._currentHit) {
  79587. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  79588. }
  79589. };
  79590. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  79591. if (this._currentMeshSelected && this._currentHit) {
  79592. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  79593. }
  79594. this._pointerDownOnMeshAsked = false;
  79595. };
  79596. VRExperienceHelperGazer.prototype._activatePointer = function () {
  79597. this._activePointer = true;
  79598. };
  79599. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  79600. this._activePointer = false;
  79601. };
  79602. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  79603. };
  79604. VRExperienceHelperGazer.prototype.dispose = function () {
  79605. this._interactionsEnabled = false;
  79606. this._teleportationEnabled = false;
  79607. };
  79608. VRExperienceHelperGazer._idCounter = 0;
  79609. return VRExperienceHelperGazer;
  79610. }());
  79611. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  79612. __extends(VRExperienceHelperControllerGazer, _super);
  79613. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  79614. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  79615. _this.webVRController = webVRController;
  79616. // Laser pointer
  79617. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  79618. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  79619. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79620. laserPointerMaterial.alpha = 0.6;
  79621. _this._laserPointer.material = laserPointerMaterial;
  79622. _this._laserPointer.rotation.x = Math.PI / 2;
  79623. _this._laserPointer.position.z = -0.5;
  79624. _this._laserPointer.isVisible = false;
  79625. _this._laserPointer.parent = webVRController.mesh;
  79626. return _this;
  79627. }
  79628. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  79629. return this.webVRController.getForwardRay(length);
  79630. };
  79631. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  79632. _super.prototype._activatePointer.call(this);
  79633. this._laserPointer.isVisible = true;
  79634. };
  79635. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  79636. _super.prototype._deactivatePointer.call(this);
  79637. this._laserPointer.isVisible = false;
  79638. };
  79639. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  79640. this._laserPointer.material.emissiveColor = color;
  79641. };
  79642. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  79643. this._laserPointer.parent = mesh;
  79644. };
  79645. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  79646. this._laserPointer.scaling.y = distance;
  79647. this._laserPointer.position.z = -distance / 2;
  79648. };
  79649. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  79650. _super.prototype.dispose.call(this);
  79651. this._laserPointer.dispose();
  79652. };
  79653. return VRExperienceHelperControllerGazer;
  79654. }(VRExperienceHelperGazer));
  79655. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  79656. __extends(VRExperienceHelperCameraGazer, _super);
  79657. function VRExperienceHelperCameraGazer(getCamera, scene) {
  79658. var _this = _super.call(this, scene) || this;
  79659. _this.getCamera = getCamera;
  79660. return _this;
  79661. }
  79662. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  79663. var camera = this.getCamera();
  79664. if (camera) {
  79665. return camera.getForwardRay(length);
  79666. }
  79667. else {
  79668. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  79669. }
  79670. };
  79671. return VRExperienceHelperCameraGazer;
  79672. }(VRExperienceHelperGazer));
  79673. /**
  79674. * Helps to quickly add VR support to an existing scene.
  79675. * See http://doc.babylonjs.com/how_to/webvr_helper
  79676. */
  79677. var VRExperienceHelper = /** @class */ (function () {
  79678. /**
  79679. * Instantiates a VRExperienceHelper.
  79680. * Helps to quickly add VR support to an existing scene.
  79681. * @param scene The scene the VRExperienceHelper belongs to.
  79682. * @param webVROptions Options to modify the vr experience helper's behavior.
  79683. */
  79684. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79685. if (webVROptions === void 0) { webVROptions = {}; }
  79686. var _this = this;
  79687. this.webVROptions = webVROptions;
  79688. // Can the system support WebVR, even if a headset isn't plugged in?
  79689. this._webVRsupported = false;
  79690. // If WebVR is supported, is a headset plugged in and are we ready to present?
  79691. this._webVRready = false;
  79692. // Are we waiting for the requestPresent callback to complete?
  79693. this._webVRrequesting = false;
  79694. // Are we presenting to the headset right now?
  79695. this._webVRpresenting = false;
  79696. // Are we presenting in the fullscreen fallback?
  79697. this._fullscreenVRpresenting = false;
  79698. /**
  79699. * Observable raised when entering VR.
  79700. */
  79701. this.onEnteringVRObservable = new BABYLON.Observable();
  79702. /**
  79703. * Observable raised when exiting VR.
  79704. */
  79705. this.onExitingVRObservable = new BABYLON.Observable();
  79706. /**
  79707. * Observable raised when controller mesh is loaded.
  79708. */
  79709. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79710. this._useCustomVRButton = false;
  79711. this._teleportationRequested = false;
  79712. this._teleportActive = false;
  79713. this._floorMeshesCollection = [];
  79714. this._rotationAllowed = true;
  79715. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  79716. this._rotationRightAsked = false;
  79717. this._rotationLeftAsked = false;
  79718. this._isDefaultTeleportationTarget = true;
  79719. this._teleportationFillColor = "#444444";
  79720. this._teleportationBorderColor = "#FFFFFF";
  79721. this._rotationAngle = 0;
  79722. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  79723. this._padSensibilityUp = 0.65;
  79724. this._padSensibilityDown = 0.35;
  79725. this.leftController = null;
  79726. this.rightController = null;
  79727. /**
  79728. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  79729. */
  79730. this.onNewMeshSelected = new BABYLON.Observable();
  79731. /**
  79732. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  79733. */
  79734. this.onNewMeshPicked = new BABYLON.Observable();
  79735. /**
  79736. * Observable raised before camera teleportation
  79737. */
  79738. this.onBeforeCameraTeleport = new BABYLON.Observable();
  79739. /**
  79740. * Observable raised after camera teleportation
  79741. */
  79742. this.onAfterCameraTeleport = new BABYLON.Observable();
  79743. /**
  79744. * Observable raised when current selected mesh gets unselected
  79745. */
  79746. this.onSelectedMeshUnselected = new BABYLON.Observable();
  79747. /**
  79748. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  79749. */
  79750. this.teleportationEnabled = true;
  79751. this._teleportationInitialized = false;
  79752. this._interactionsEnabled = false;
  79753. this._interactionsRequested = false;
  79754. this._displayGaze = true;
  79755. this._displayLaserPointer = true;
  79756. this._onResize = function () {
  79757. _this.moveButtonToBottomRight();
  79758. if (_this._fullscreenVRpresenting && _this._webVRready) {
  79759. _this.exitVR();
  79760. }
  79761. };
  79762. this._onFullscreenChange = function () {
  79763. if (document.fullscreen !== undefined) {
  79764. _this._fullscreenVRpresenting = document.fullscreen;
  79765. }
  79766. else if (document.mozFullScreen !== undefined) {
  79767. _this._fullscreenVRpresenting = document.mozFullScreen;
  79768. }
  79769. else if (document.webkitIsFullScreen !== undefined) {
  79770. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  79771. }
  79772. else if (document.msIsFullScreen !== undefined) {
  79773. _this._fullscreenVRpresenting = document.msIsFullScreen;
  79774. }
  79775. if (!_this._fullscreenVRpresenting && _this._canvas) {
  79776. _this.exitVR();
  79777. if (!_this._useCustomVRButton) {
  79778. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  79779. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  79780. }
  79781. }
  79782. };
  79783. this.beforeRender = function () {
  79784. if (_this.leftController && _this.leftController._activePointer) {
  79785. _this._castRayAndSelectObject(_this.leftController);
  79786. }
  79787. if (_this.rightController && _this.rightController._activePointer) {
  79788. _this._castRayAndSelectObject(_this.rightController);
  79789. }
  79790. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  79791. _this._castRayAndSelectObject(_this._cameraGazer);
  79792. }
  79793. else {
  79794. _this._cameraGazer._gazeTracker.isVisible = false;
  79795. }
  79796. };
  79797. this._onNewGamepadConnected = function (gamepad) {
  79798. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79799. if (gamepad.leftStick) {
  79800. gamepad.onleftstickchanged(function (stickValues) {
  79801. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  79802. // Listening to classic/xbox gamepad only if no VR controller is active
  79803. if ((!_this.leftController && !_this.rightController) ||
  79804. ((_this.leftController && !_this.leftController._activePointer) &&
  79805. (_this.rightController && !_this.rightController._activePointer))) {
  79806. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  79807. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  79808. }
  79809. }
  79810. });
  79811. }
  79812. if (gamepad.rightStick) {
  79813. gamepad.onrightstickchanged(function (stickValues) {
  79814. if (_this._teleportationInitialized) {
  79815. _this._checkRotate(stickValues, _this._cameraGazer);
  79816. }
  79817. });
  79818. }
  79819. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  79820. gamepad.onbuttondown(function (buttonPressed) {
  79821. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79822. _this._cameraGazer._selectionPointerDown();
  79823. }
  79824. });
  79825. gamepad.onbuttonup(function (buttonPressed) {
  79826. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79827. _this._cameraGazer._selectionPointerUp();
  79828. }
  79829. });
  79830. }
  79831. }
  79832. else {
  79833. var webVRController = gamepad;
  79834. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  79835. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  79836. _this.rightController = controller;
  79837. }
  79838. else {
  79839. _this.leftController = controller;
  79840. }
  79841. _this._tryEnableInteractionOnController(controller);
  79842. }
  79843. };
  79844. // 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
  79845. this._tryEnableInteractionOnController = function (controller) {
  79846. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  79847. _this._enableInteractionOnController(controller);
  79848. }
  79849. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  79850. _this._enableTeleportationOnController(controller);
  79851. }
  79852. };
  79853. this._onNewGamepadDisconnected = function (gamepad) {
  79854. if (gamepad instanceof BABYLON.WebVRController) {
  79855. if (gamepad.hand === "left" && _this.leftController != null) {
  79856. _this.leftController.dispose();
  79857. _this.leftController = null;
  79858. }
  79859. if (gamepad.hand === "right" && _this.rightController != null) {
  79860. _this.rightController.dispose();
  79861. _this.rightController = null;
  79862. }
  79863. }
  79864. };
  79865. this._workingVector = BABYLON.Vector3.Zero();
  79866. this._workingQuaternion = BABYLON.Quaternion.Identity();
  79867. this._workingMatrix = BABYLON.Matrix.Identity();
  79868. this._scene = scene;
  79869. this._canvas = scene.getEngine().getRenderingCanvas();
  79870. // Parse options
  79871. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  79872. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  79873. }
  79874. if (webVROptions.createDeviceOrientationCamera === undefined) {
  79875. webVROptions.createDeviceOrientationCamera = true;
  79876. }
  79877. if (webVROptions.defaultHeight === undefined) {
  79878. webVROptions.defaultHeight = 1.7;
  79879. }
  79880. if (webVROptions.useCustomVRButton) {
  79881. this._useCustomVRButton = true;
  79882. if (webVROptions.customVRButton) {
  79883. this._btnVR = webVROptions.customVRButton;
  79884. }
  79885. }
  79886. if (webVROptions.rayLength) {
  79887. this._rayLength = webVROptions.rayLength;
  79888. }
  79889. this._defaultHeight = webVROptions.defaultHeight;
  79890. // Set position
  79891. if (this._scene.activeCamera) {
  79892. this._position = this._scene.activeCamera.position.clone();
  79893. }
  79894. else {
  79895. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  79896. }
  79897. // Set non-vr camera
  79898. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  79899. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  79900. // Copy data from existing camera
  79901. if (this._scene.activeCamera) {
  79902. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  79903. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  79904. // Set rotation from previous camera
  79905. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  79906. var targetCamera = this._scene.activeCamera;
  79907. if (targetCamera.rotationQuaternion) {
  79908. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  79909. }
  79910. else {
  79911. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  79912. }
  79913. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  79914. }
  79915. }
  79916. this._scene.activeCamera = this._deviceOrientationCamera;
  79917. if (this._canvas) {
  79918. this._scene.activeCamera.attachControl(this._canvas);
  79919. }
  79920. }
  79921. else {
  79922. this._existingCamera = this._scene.activeCamera;
  79923. }
  79924. // Create VR cameras
  79925. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79926. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  79927. }
  79928. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  79929. this._webVRCamera.useStandingMatrix();
  79930. // Create default button
  79931. if (!this._useCustomVRButton) {
  79932. this._btnVR = document.createElement("BUTTON");
  79933. this._btnVR.className = "babylonVRicon";
  79934. this._btnVR.id = "babylonVRiconbtn";
  79935. this._btnVR.title = "Click to switch to VR";
  79936. 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) }";
  79937. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  79938. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  79939. // css += ".babylonVRicon.vrdisplaysupported { }";
  79940. // css += ".babylonVRicon.vrdisplayready { }";
  79941. // css += ".babylonVRicon.vrdisplayrequesting { }";
  79942. var style = document.createElement('style');
  79943. style.appendChild(document.createTextNode(css));
  79944. document.getElementsByTagName('head')[0].appendChild(style);
  79945. this.moveButtonToBottomRight();
  79946. }
  79947. // VR button click event
  79948. if (this._btnVR) {
  79949. this._btnVR.addEventListener("click", function () {
  79950. if (!_this.isInVRMode) {
  79951. _this.enterVR();
  79952. }
  79953. else {
  79954. _this.exitVR();
  79955. }
  79956. });
  79957. }
  79958. // Window events
  79959. window.addEventListener("resize", this._onResize);
  79960. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79961. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79962. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79963. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79964. // Display vr button when headset is connected
  79965. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79966. this.displayVRButton();
  79967. }
  79968. else {
  79969. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79970. if (e.vrDisplay) {
  79971. _this.displayVRButton();
  79972. }
  79973. });
  79974. }
  79975. // Exiting VR mode using 'ESC' key on desktop
  79976. this._onKeyDown = function (event) {
  79977. if (event.keyCode === 27 && _this.isInVRMode) {
  79978. _this.exitVR();
  79979. }
  79980. };
  79981. document.addEventListener("keydown", this._onKeyDown);
  79982. // Exiting VR mode double tapping the touch screen
  79983. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79984. if (_this.isInVRMode) {
  79985. _this.exitVR();
  79986. if (_this._fullscreenVRpresenting) {
  79987. _this._scene.getEngine().switchFullscreen(true);
  79988. }
  79989. }
  79990. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79991. // Listen for WebVR display changes
  79992. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79993. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79994. this._onVRRequestPresentStart = function () {
  79995. _this._webVRrequesting = true;
  79996. _this.updateButtonVisibility();
  79997. };
  79998. this._onVRRequestPresentComplete = function (success) {
  79999. _this._webVRrequesting = false;
  80000. _this.updateButtonVisibility();
  80001. };
  80002. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80003. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80004. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80005. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80006. scene.onDisposeObservable.add(function () {
  80007. _this.dispose();
  80008. });
  80009. // Gamepad connection events
  80010. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80011. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80012. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80013. this.updateButtonVisibility();
  80014. //create easing functions
  80015. this._circleEase = new BABYLON.CircleEase();
  80016. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80017. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80018. }
  80019. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80020. /** Return this.onEnteringVRObservable
  80021. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80022. */
  80023. get: function () {
  80024. return this.onEnteringVRObservable;
  80025. },
  80026. enumerable: true,
  80027. configurable: true
  80028. });
  80029. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80030. /** Return this.onExitingVRObservable
  80031. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80032. */
  80033. get: function () {
  80034. return this.onExitingVRObservable;
  80035. },
  80036. enumerable: true,
  80037. configurable: true
  80038. });
  80039. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80040. /** Return this.onControllerMeshLoadedObservable
  80041. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80042. */
  80043. get: function () {
  80044. return this.onControllerMeshLoadedObservable;
  80045. },
  80046. enumerable: true,
  80047. configurable: true
  80048. });
  80049. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80050. /**
  80051. * The mesh used to display where the user is going to teleport.
  80052. */
  80053. get: function () {
  80054. return this._teleportationTarget;
  80055. },
  80056. /**
  80057. * Sets the mesh to be used to display where the user is going to teleport.
  80058. */
  80059. set: function (value) {
  80060. if (value) {
  80061. value.name = "teleportationTarget";
  80062. this._isDefaultTeleportationTarget = false;
  80063. this._teleportationTarget = value;
  80064. }
  80065. },
  80066. enumerable: true,
  80067. configurable: true
  80068. });
  80069. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80070. /**
  80071. * The mesh used to display where the user is selecting,
  80072. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80073. * See http://doc.babylonjs.com/resources/baking_transformations
  80074. */
  80075. get: function () {
  80076. return this._cameraGazer._gazeTracker;
  80077. },
  80078. set: function (value) {
  80079. if (value) {
  80080. this._cameraGazer._gazeTracker = value;
  80081. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80082. this._cameraGazer._gazeTracker.isPickable = false;
  80083. this._cameraGazer._gazeTracker.isVisible = false;
  80084. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80085. if (this.leftController) {
  80086. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80087. }
  80088. if (this.rightController) {
  80089. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80090. }
  80091. }
  80092. },
  80093. enumerable: true,
  80094. configurable: true
  80095. });
  80096. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80097. /**
  80098. * If the ray of the gaze should be displayed.
  80099. */
  80100. get: function () {
  80101. return this._displayGaze;
  80102. },
  80103. /**
  80104. * Sets if the ray of the gaze should be displayed.
  80105. */
  80106. set: function (value) {
  80107. this._displayGaze = value;
  80108. if (!value) {
  80109. this._cameraGazer._gazeTracker.isVisible = false;
  80110. if (this.leftController) {
  80111. this.leftController._gazeTracker.isVisible = false;
  80112. }
  80113. if (this.rightController) {
  80114. this.rightController._gazeTracker.isVisible = false;
  80115. }
  80116. }
  80117. },
  80118. enumerable: true,
  80119. configurable: true
  80120. });
  80121. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80122. /**
  80123. * If the ray of the LaserPointer should be displayed.
  80124. */
  80125. get: function () {
  80126. return this._displayLaserPointer;
  80127. },
  80128. /**
  80129. * Sets if the ray of the LaserPointer should be displayed.
  80130. */
  80131. set: function (value) {
  80132. this._displayLaserPointer = value;
  80133. if (!value) {
  80134. if (this.rightController) {
  80135. this.rightController._deactivatePointer();
  80136. this.rightController._gazeTracker.isVisible = false;
  80137. }
  80138. if (this.leftController) {
  80139. this.leftController._deactivatePointer();
  80140. this.leftController._gazeTracker.isVisible = false;
  80141. }
  80142. }
  80143. else {
  80144. if (this.rightController) {
  80145. this.rightController._activatePointer();
  80146. }
  80147. else if (this.leftController) {
  80148. this.leftController._activatePointer();
  80149. }
  80150. }
  80151. },
  80152. enumerable: true,
  80153. configurable: true
  80154. });
  80155. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80156. /**
  80157. * The deviceOrientationCamera used as the camera when not in VR.
  80158. */
  80159. get: function () {
  80160. return this._deviceOrientationCamera;
  80161. },
  80162. enumerable: true,
  80163. configurable: true
  80164. });
  80165. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80166. /**
  80167. * Based on the current WebVR support, returns the current VR camera used.
  80168. */
  80169. get: function () {
  80170. if (this._webVRready) {
  80171. return this._webVRCamera;
  80172. }
  80173. else {
  80174. return this._scene.activeCamera;
  80175. }
  80176. },
  80177. enumerable: true,
  80178. configurable: true
  80179. });
  80180. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80181. /**
  80182. * The webVRCamera which is used when in VR.
  80183. */
  80184. get: function () {
  80185. return this._webVRCamera;
  80186. },
  80187. enumerable: true,
  80188. configurable: true
  80189. });
  80190. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80191. /**
  80192. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80193. */
  80194. get: function () {
  80195. return this._vrDeviceOrientationCamera;
  80196. },
  80197. enumerable: true,
  80198. configurable: true
  80199. });
  80200. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80201. get: function () {
  80202. var result = this._cameraGazer._teleportationRequestInitiated
  80203. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80204. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80205. return result;
  80206. },
  80207. enumerable: true,
  80208. configurable: true
  80209. });
  80210. // Raised when one of the controller has loaded successfully its associated default mesh
  80211. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80212. if (this.leftController && this.leftController.webVRController == webVRController) {
  80213. this._tryEnableInteractionOnController(this.leftController);
  80214. }
  80215. if (this.rightController && this.rightController.webVRController == webVRController) {
  80216. this._tryEnableInteractionOnController(this.rightController);
  80217. }
  80218. try {
  80219. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80220. }
  80221. catch (err) {
  80222. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80223. }
  80224. };
  80225. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80226. /**
  80227. * Gets a value indicating if we are currently in VR mode.
  80228. */
  80229. get: function () {
  80230. return this._webVRpresenting || this._fullscreenVRpresenting;
  80231. },
  80232. enumerable: true,
  80233. configurable: true
  80234. });
  80235. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80236. var vrDisplay = this._scene.getEngine().getVRDevice();
  80237. if (vrDisplay) {
  80238. var wasPresenting = this._webVRpresenting;
  80239. // A VR display is connected
  80240. this._webVRpresenting = vrDisplay.isPresenting;
  80241. if (wasPresenting && !this._webVRpresenting)
  80242. this.exitVR();
  80243. }
  80244. else {
  80245. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80246. }
  80247. this.updateButtonVisibility();
  80248. };
  80249. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80250. this._webVRsupported = eventArgs.vrSupported;
  80251. this._webVRready = !!eventArgs.vrDisplay;
  80252. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80253. this.updateButtonVisibility();
  80254. };
  80255. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80256. if (this._canvas && !this._useCustomVRButton) {
  80257. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80258. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80259. }
  80260. };
  80261. VRExperienceHelper.prototype.displayVRButton = function () {
  80262. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80263. document.body.appendChild(this._btnVR);
  80264. this._btnVRDisplayed = true;
  80265. }
  80266. };
  80267. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80268. if (!this._btnVR || this._useCustomVRButton) {
  80269. return;
  80270. }
  80271. this._btnVR.className = "babylonVRicon";
  80272. if (this.isInVRMode) {
  80273. this._btnVR.className += " vrdisplaypresenting";
  80274. }
  80275. else {
  80276. if (this._webVRready)
  80277. this._btnVR.className += " vrdisplayready";
  80278. if (this._webVRsupported)
  80279. this._btnVR.className += " vrdisplaysupported";
  80280. if (this._webVRrequesting)
  80281. this._btnVR.className += " vrdisplayrequesting";
  80282. }
  80283. };
  80284. /**
  80285. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80286. * Otherwise, will use the fullscreen API.
  80287. */
  80288. VRExperienceHelper.prototype.enterVR = function () {
  80289. if (this.onEnteringVRObservable) {
  80290. try {
  80291. this.onEnteringVRObservable.notifyObservers(this);
  80292. }
  80293. catch (err) {
  80294. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80295. }
  80296. }
  80297. if (this._scene.activeCamera) {
  80298. this._position = this._scene.activeCamera.position.clone();
  80299. // make sure that we return to the last active camera
  80300. this._existingCamera = this._scene.activeCamera;
  80301. }
  80302. if (this._webVRrequesting)
  80303. return;
  80304. // If WebVR is supported and a headset is connected
  80305. if (this._webVRready) {
  80306. if (!this._webVRpresenting) {
  80307. this._webVRCamera.position = this._position;
  80308. this._scene.activeCamera = this._webVRCamera;
  80309. }
  80310. }
  80311. else if (this._vrDeviceOrientationCamera) {
  80312. this._vrDeviceOrientationCamera.position = this._position;
  80313. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80314. this._scene.getEngine().switchFullscreen(true);
  80315. this.updateButtonVisibility();
  80316. }
  80317. if (this._scene.activeCamera && this._canvas) {
  80318. this._scene.activeCamera.attachControl(this._canvas);
  80319. }
  80320. if (this._interactionsEnabled) {
  80321. this._scene.registerBeforeRender(this.beforeRender);
  80322. }
  80323. };
  80324. /**
  80325. * Attempt to exit VR, or fullscreen.
  80326. */
  80327. VRExperienceHelper.prototype.exitVR = function () {
  80328. if (this.onExitingVRObservable) {
  80329. try {
  80330. this.onExitingVRObservable.notifyObservers(this);
  80331. }
  80332. catch (err) {
  80333. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80334. }
  80335. }
  80336. if (this._webVRpresenting) {
  80337. this._scene.getEngine().disableVR();
  80338. }
  80339. if (this._scene.activeCamera) {
  80340. this._position = this._scene.activeCamera.position.clone();
  80341. }
  80342. if (this._deviceOrientationCamera) {
  80343. this._deviceOrientationCamera.position = this._position;
  80344. this._scene.activeCamera = this._deviceOrientationCamera;
  80345. if (this._canvas) {
  80346. this._scene.activeCamera.attachControl(this._canvas);
  80347. }
  80348. }
  80349. else if (this._existingCamera) {
  80350. this._existingCamera.position = this._position;
  80351. this._scene.activeCamera = this._existingCamera;
  80352. }
  80353. this.updateButtonVisibility();
  80354. if (this._interactionsEnabled) {
  80355. this._scene.unregisterBeforeRender(this.beforeRender);
  80356. }
  80357. };
  80358. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80359. /**
  80360. * The position of the vr experience helper.
  80361. */
  80362. get: function () {
  80363. return this._position;
  80364. },
  80365. /**
  80366. * Sets the position of the vr experience helper.
  80367. */
  80368. set: function (value) {
  80369. this._position = value;
  80370. if (this._scene.activeCamera) {
  80371. this._scene.activeCamera.position = value;
  80372. }
  80373. },
  80374. enumerable: true,
  80375. configurable: true
  80376. });
  80377. /**
  80378. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80379. */
  80380. VRExperienceHelper.prototype.enableInteractions = function () {
  80381. var _this = this;
  80382. if (!this._interactionsEnabled) {
  80383. this._interactionsRequested = true;
  80384. if (this.leftController) {
  80385. this._enableInteractionOnController(this.leftController);
  80386. }
  80387. if (this.rightController) {
  80388. this._enableInteractionOnController(this.rightController);
  80389. }
  80390. this.raySelectionPredicate = function (mesh) {
  80391. return mesh.isVisible;
  80392. };
  80393. this.meshSelectionPredicate = function (mesh) {
  80394. return true;
  80395. };
  80396. this._raySelectionPredicate = function (mesh) {
  80397. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80398. && mesh.name.indexOf("teleportationTarget") === -1
  80399. && mesh.name.indexOf("torusTeleportation") === -1
  80400. && mesh.name.indexOf("laserPointer") === -1)) {
  80401. return _this.raySelectionPredicate(mesh);
  80402. }
  80403. return false;
  80404. };
  80405. this._interactionsEnabled = true;
  80406. }
  80407. };
  80408. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80409. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80410. if (this._floorMeshesCollection[i].id === mesh.id) {
  80411. return true;
  80412. }
  80413. }
  80414. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80415. return true;
  80416. }
  80417. return false;
  80418. };
  80419. /**
  80420. * Adds a floor mesh to be used for teleportation.
  80421. * @param floorMesh the mesh to be used for teleportation.
  80422. */
  80423. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80424. if (!this._floorMeshesCollection) {
  80425. return;
  80426. }
  80427. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80428. return;
  80429. }
  80430. this._floorMeshesCollection.push(floorMesh);
  80431. };
  80432. /**
  80433. * Removes a floor mesh from being used for teleportation.
  80434. * @param floorMesh the mesh to be removed.
  80435. */
  80436. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80437. if (!this._floorMeshesCollection) {
  80438. return;
  80439. }
  80440. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80441. if (meshIndex !== -1) {
  80442. this._floorMeshesCollection.splice(meshIndex, 1);
  80443. }
  80444. };
  80445. /**
  80446. * Enables interactions and teleportation using the VR controllers and gaze.
  80447. * @param vrTeleportationOptions options to modify teleportation behavior.
  80448. */
  80449. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80450. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80451. if (!this._teleportationInitialized) {
  80452. this._teleportationRequested = true;
  80453. this.enableInteractions();
  80454. if (vrTeleportationOptions.floorMeshName) {
  80455. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80456. }
  80457. if (vrTeleportationOptions.floorMeshes) {
  80458. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80459. }
  80460. if (this.leftController != null) {
  80461. this._enableTeleportationOnController(this.leftController);
  80462. }
  80463. if (this.rightController != null) {
  80464. this._enableTeleportationOnController(this.rightController);
  80465. }
  80466. // Creates an image processing post process for the vignette not relying
  80467. // on the main scene configuration for image processing to reduce setup and spaces
  80468. // (gamma/linear) conflicts.
  80469. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80470. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80471. imageProcessingConfiguration.vignetteEnabled = true;
  80472. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80473. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80474. this._teleportationInitialized = true;
  80475. if (this._isDefaultTeleportationTarget) {
  80476. this._createTeleportationCircles();
  80477. }
  80478. }
  80479. };
  80480. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  80481. var _this = this;
  80482. var controllerMesh = controller.webVRController.mesh;
  80483. if (controllerMesh) {
  80484. var makeNotPick = function (root) {
  80485. root.name += " laserPointer";
  80486. root.getChildMeshes().forEach(function (c) {
  80487. makeNotPick(c);
  80488. });
  80489. };
  80490. makeNotPick(controllerMesh);
  80491. var childMeshes = controllerMesh.getChildMeshes();
  80492. for (var i = 0; i < childMeshes.length; i++) {
  80493. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80494. controllerMesh = childMeshes[i];
  80495. break;
  80496. }
  80497. }
  80498. controller._setLaserPointerParent(controllerMesh);
  80499. controller._interactionsEnabled = true;
  80500. controller._activatePointer();
  80501. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80502. // Enabling / disabling laserPointer
  80503. if (_this._displayLaserPointer && stateObject.value === 1) {
  80504. if (controller._activePointer) {
  80505. controller._deactivatePointer();
  80506. }
  80507. else {
  80508. controller._activatePointer();
  80509. }
  80510. if (_this.displayGaze) {
  80511. controller._gazeTracker.isVisible = controller._activePointer;
  80512. }
  80513. }
  80514. });
  80515. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80516. if (!controller._pointerDownOnMeshAsked) {
  80517. if (stateObject.value > _this._padSensibilityUp) {
  80518. controller._selectionPointerDown();
  80519. }
  80520. }
  80521. else if (stateObject.value < _this._padSensibilityDown) {
  80522. controller._selectionPointerUp();
  80523. }
  80524. });
  80525. }
  80526. };
  80527. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  80528. // Dont teleport if another gaze already requested teleportation
  80529. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  80530. return;
  80531. }
  80532. if (!gazer._teleportationRequestInitiated) {
  80533. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  80534. gazer._activatePointer();
  80535. gazer._teleportationRequestInitiated = true;
  80536. }
  80537. }
  80538. else {
  80539. // Listening to the proper controller values changes to confirm teleportation
  80540. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80541. if (this._teleportActive) {
  80542. this._teleportCamera(this._haloCenter);
  80543. }
  80544. gazer._teleportationRequestInitiated = false;
  80545. }
  80546. }
  80547. };
  80548. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  80549. // Only rotate when user is not currently selecting a teleportation location
  80550. if (gazer._teleportationRequestInitiated) {
  80551. return;
  80552. }
  80553. if (!this._rotationLeftAsked) {
  80554. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  80555. this._rotationLeftAsked = true;
  80556. if (this._rotationAllowed) {
  80557. this._rotateCamera(false);
  80558. }
  80559. }
  80560. }
  80561. else {
  80562. if (stateObject.x > -this._padSensibilityDown) {
  80563. this._rotationLeftAsked = false;
  80564. }
  80565. }
  80566. if (!this._rotationRightAsked) {
  80567. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  80568. this._rotationRightAsked = true;
  80569. if (this._rotationAllowed) {
  80570. this._rotateCamera(true);
  80571. }
  80572. }
  80573. }
  80574. else {
  80575. if (stateObject.x < this._padSensibilityDown) {
  80576. this._rotationRightAsked = false;
  80577. }
  80578. }
  80579. };
  80580. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  80581. // Only teleport backwards when user is not currently selecting a teleportation location
  80582. if (gazer._teleportationRequestInitiated) {
  80583. return;
  80584. }
  80585. // Teleport backwards
  80586. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  80587. if (!gazer._teleportationBackRequestInitiated) {
  80588. if (!this.currentVRCamera) {
  80589. return;
  80590. }
  80591. // Get rotation and position of the current camera
  80592. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80593. var position = this.currentVRCamera.position;
  80594. // If the camera has device position, use that instead
  80595. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80596. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80597. position = this.currentVRCamera.devicePosition;
  80598. }
  80599. // Get matrix with only the y rotation of the device rotation
  80600. rotation.toEulerAnglesToRef(this._workingVector);
  80601. this._workingVector.z = 0;
  80602. this._workingVector.x = 0;
  80603. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80604. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80605. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80606. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80607. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80608. var ray = new BABYLON.Ray(position, this._workingVector);
  80609. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80610. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80611. this._teleportCamera(hit.pickedPoint);
  80612. }
  80613. gazer._teleportationBackRequestInitiated = true;
  80614. }
  80615. }
  80616. else {
  80617. gazer._teleportationBackRequestInitiated = false;
  80618. }
  80619. };
  80620. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  80621. var _this = this;
  80622. var controllerMesh = controller.webVRController.mesh;
  80623. if (controllerMesh) {
  80624. if (!controller._interactionsEnabled) {
  80625. this._enableInteractionOnController(controller);
  80626. }
  80627. controller._interactionsEnabled = true;
  80628. controller._teleportationEnabled = true;
  80629. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80630. controller._dpadPressed = false;
  80631. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80632. controller._dpadPressed = stateObject.pressed;
  80633. if (!controller._dpadPressed) {
  80634. _this._rotationLeftAsked = false;
  80635. _this._rotationRightAsked = false;
  80636. controller._teleportationBackRequestInitiated = false;
  80637. }
  80638. });
  80639. }
  80640. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80641. if (_this.teleportationEnabled) {
  80642. _this._checkTeleportBackwards(stateObject, controller);
  80643. _this._checkTeleportWithRay(stateObject, controller);
  80644. }
  80645. _this._checkRotate(stateObject, controller);
  80646. });
  80647. }
  80648. };
  80649. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80650. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80651. this._teleportationTarget.isPickable = false;
  80652. var length = 512;
  80653. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80654. dynamicTexture.hasAlpha = true;
  80655. var context = dynamicTexture.getContext();
  80656. var centerX = length / 2;
  80657. var centerY = length / 2;
  80658. var radius = 200;
  80659. context.beginPath();
  80660. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80661. context.fillStyle = this._teleportationFillColor;
  80662. context.fill();
  80663. context.lineWidth = 10;
  80664. context.strokeStyle = this._teleportationBorderColor;
  80665. context.stroke();
  80666. context.closePath();
  80667. dynamicTexture.update();
  80668. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80669. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80670. this._teleportationTarget.material = teleportationCircleMaterial;
  80671. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80672. torus.isPickable = false;
  80673. torus.parent = this._teleportationTarget;
  80674. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80675. var keys = [];
  80676. keys.push({
  80677. frame: 0,
  80678. value: 0
  80679. });
  80680. keys.push({
  80681. frame: 30,
  80682. value: 0.4
  80683. });
  80684. keys.push({
  80685. frame: 60,
  80686. value: 0
  80687. });
  80688. animationInnerCircle.setKeys(keys);
  80689. var easingFunction = new BABYLON.SineEase();
  80690. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80691. animationInnerCircle.setEasingFunction(easingFunction);
  80692. torus.animations = [];
  80693. torus.animations.push(animationInnerCircle);
  80694. this._scene.beginAnimation(torus, 0, 60, true);
  80695. this._hideTeleportationTarget();
  80696. };
  80697. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  80698. this._teleportActive = true;
  80699. if (this._teleportationInitialized) {
  80700. this._teleportationTarget.isVisible = true;
  80701. if (this._isDefaultTeleportationTarget) {
  80702. this._teleportationTarget.getChildren()[0].isVisible = true;
  80703. }
  80704. }
  80705. };
  80706. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  80707. this._teleportActive = false;
  80708. if (this._teleportationInitialized) {
  80709. this._teleportationTarget.isVisible = false;
  80710. if (this._isDefaultTeleportationTarget) {
  80711. this._teleportationTarget.getChildren()[0].isVisible = false;
  80712. }
  80713. }
  80714. };
  80715. VRExperienceHelper.prototype._rotateCamera = function (right) {
  80716. var _this = this;
  80717. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80718. return;
  80719. }
  80720. if (right) {
  80721. this._rotationAngle++;
  80722. }
  80723. else {
  80724. this._rotationAngle--;
  80725. }
  80726. this.currentVRCamera.animations = [];
  80727. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  80728. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80729. var animationRotationKeys = [];
  80730. animationRotationKeys.push({
  80731. frame: 0,
  80732. value: this.currentVRCamera.rotationQuaternion
  80733. });
  80734. animationRotationKeys.push({
  80735. frame: 6,
  80736. value: target
  80737. });
  80738. animationRotation.setKeys(animationRotationKeys);
  80739. animationRotation.setEasingFunction(this._circleEase);
  80740. this.currentVRCamera.animations.push(animationRotation);
  80741. this._postProcessMove.animations = [];
  80742. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80743. var vignetteWeightKeys = [];
  80744. vignetteWeightKeys.push({
  80745. frame: 0,
  80746. value: 0
  80747. });
  80748. vignetteWeightKeys.push({
  80749. frame: 3,
  80750. value: 4
  80751. });
  80752. vignetteWeightKeys.push({
  80753. frame: 6,
  80754. value: 0
  80755. });
  80756. animationPP.setKeys(vignetteWeightKeys);
  80757. animationPP.setEasingFunction(this._circleEase);
  80758. this._postProcessMove.animations.push(animationPP);
  80759. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80760. var vignetteStretchKeys = [];
  80761. vignetteStretchKeys.push({
  80762. frame: 0,
  80763. value: 0
  80764. });
  80765. vignetteStretchKeys.push({
  80766. frame: 3,
  80767. value: 10
  80768. });
  80769. vignetteStretchKeys.push({
  80770. frame: 6,
  80771. value: 0
  80772. });
  80773. animationPP2.setKeys(vignetteStretchKeys);
  80774. animationPP2.setEasingFunction(this._circleEase);
  80775. this._postProcessMove.animations.push(animationPP2);
  80776. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80777. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80778. this._postProcessMove.samples = 4;
  80779. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80780. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  80781. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80782. });
  80783. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  80784. };
  80785. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  80786. if (hit.pickedPoint) {
  80787. if (gazer._teleportationRequestInitiated) {
  80788. this._displayTeleportationTarget();
  80789. this._haloCenter.copyFrom(hit.pickedPoint);
  80790. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  80791. }
  80792. var pickNormal = hit.getNormal(true, false);
  80793. if (pickNormal) {
  80794. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80795. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80796. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  80797. }
  80798. this._teleportationTarget.position.y += 0.1;
  80799. }
  80800. };
  80801. VRExperienceHelper.prototype._teleportCamera = function (location) {
  80802. var _this = this;
  80803. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80804. return;
  80805. }
  80806. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  80807. // offset of the headset from the anchor.
  80808. if (this.webVRCamera.leftCamera) {
  80809. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  80810. this._workingVector.subtractInPlace(this.webVRCamera.position);
  80811. location.subtractToRef(this._workingVector, this._workingVector);
  80812. }
  80813. else {
  80814. this._workingVector.copyFrom(location);
  80815. }
  80816. // Add height to account for user's height offset
  80817. if (this.isInVRMode) {
  80818. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  80819. }
  80820. else {
  80821. this._workingVector.y += this._defaultHeight;
  80822. }
  80823. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  80824. // Create animation from the camera's position to the new location
  80825. this.currentVRCamera.animations = [];
  80826. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80827. var animationCameraTeleportationKeys = [{
  80828. frame: 0,
  80829. value: this.currentVRCamera.position
  80830. },
  80831. {
  80832. frame: 11,
  80833. value: this._workingVector
  80834. }
  80835. ];
  80836. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  80837. animationCameraTeleportation.setEasingFunction(this._circleEase);
  80838. this.currentVRCamera.animations.push(animationCameraTeleportation);
  80839. this._postProcessMove.animations = [];
  80840. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80841. var vignetteWeightKeys = [];
  80842. vignetteWeightKeys.push({
  80843. frame: 0,
  80844. value: 0
  80845. });
  80846. vignetteWeightKeys.push({
  80847. frame: 5,
  80848. value: 8
  80849. });
  80850. vignetteWeightKeys.push({
  80851. frame: 11,
  80852. value: 0
  80853. });
  80854. animationPP.setKeys(vignetteWeightKeys);
  80855. this._postProcessMove.animations.push(animationPP);
  80856. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80857. var vignetteStretchKeys = [];
  80858. vignetteStretchKeys.push({
  80859. frame: 0,
  80860. value: 0
  80861. });
  80862. vignetteStretchKeys.push({
  80863. frame: 5,
  80864. value: 10
  80865. });
  80866. vignetteStretchKeys.push({
  80867. frame: 11,
  80868. value: 0
  80869. });
  80870. animationPP2.setKeys(vignetteStretchKeys);
  80871. this._postProcessMove.animations.push(animationPP2);
  80872. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80873. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80874. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80875. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  80876. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80877. });
  80878. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  80879. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  80880. });
  80881. this._hideTeleportationTarget();
  80882. };
  80883. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  80884. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80885. return;
  80886. }
  80887. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  80888. // Moving the gazeTracker on the mesh face targetted
  80889. if (hit && hit.pickedPoint) {
  80890. if (this._displayGaze) {
  80891. var multiplier = 1;
  80892. gazer._gazeTracker.isVisible = true;
  80893. if (gazer._isActionableMesh) {
  80894. multiplier = 3;
  80895. }
  80896. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  80897. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  80898. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  80899. var pickNormal = hit.getNormal();
  80900. // To avoid z-fighting
  80901. var deltaFighting = 0.002;
  80902. if (pickNormal) {
  80903. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80904. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80905. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  80906. }
  80907. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  80908. if (gazer._gazeTracker.position.x < 0) {
  80909. gazer._gazeTracker.position.x += deltaFighting;
  80910. }
  80911. else {
  80912. gazer._gazeTracker.position.x -= deltaFighting;
  80913. }
  80914. if (gazer._gazeTracker.position.y < 0) {
  80915. gazer._gazeTracker.position.y += deltaFighting;
  80916. }
  80917. else {
  80918. gazer._gazeTracker.position.y -= deltaFighting;
  80919. }
  80920. if (gazer._gazeTracker.position.z < 0) {
  80921. gazer._gazeTracker.position.z += deltaFighting;
  80922. }
  80923. else {
  80924. gazer._gazeTracker.position.z -= deltaFighting;
  80925. }
  80926. }
  80927. // Changing the size of the laser pointer based on the distance from the targetted point
  80928. gazer._updatePointerDistance(hit.distance);
  80929. }
  80930. else {
  80931. gazer._gazeTracker.isVisible = false;
  80932. }
  80933. if (hit && hit.pickedMesh) {
  80934. gazer._currentHit = hit;
  80935. if (gazer._pointerDownOnMeshAsked) {
  80936. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  80937. }
  80938. // The object selected is the floor, we're in a teleportation scenario
  80939. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80940. // Moving the teleportation area to this targetted point
  80941. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80942. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  80943. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  80944. }
  80945. gazer._currentMeshSelected = null;
  80946. if (gazer._teleportationRequestInitiated) {
  80947. this._moveTeleportationSelectorTo(hit, gazer);
  80948. }
  80949. return;
  80950. }
  80951. // If not, we're in a selection scenario
  80952. //this._teleportationAllowed = false;
  80953. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  80954. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80955. this.onNewMeshPicked.notifyObservers(hit);
  80956. gazer._currentMeshSelected = hit.pickedMesh;
  80957. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80958. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80959. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80960. gazer._isActionableMesh = true;
  80961. }
  80962. else {
  80963. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80964. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80965. gazer._isActionableMesh = false;
  80966. }
  80967. try {
  80968. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  80969. }
  80970. catch (err) {
  80971. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80972. }
  80973. }
  80974. else {
  80975. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  80976. gazer._currentMeshSelected = null;
  80977. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80978. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80979. }
  80980. }
  80981. }
  80982. else {
  80983. gazer._currentHit = null;
  80984. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  80985. gazer._currentMeshSelected = null;
  80986. //this._teleportationAllowed = false;
  80987. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80988. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80989. }
  80990. };
  80991. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  80992. if (mesh) {
  80993. this.onSelectedMeshUnselected.notifyObservers(mesh);
  80994. }
  80995. };
  80996. /**
  80997. * Sets the color of the laser ray from the vr controllers.
  80998. * @param color new color for the ray.
  80999. */
  81000. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81001. if (this.leftController) {
  81002. this.leftController._setLaserPointerColor(color);
  81003. }
  81004. if (this.rightController) {
  81005. this.rightController._setLaserPointerColor(color);
  81006. }
  81007. };
  81008. /**
  81009. * Sets the color of the ray from the vr headsets gaze.
  81010. * @param color new color for the ray.
  81011. */
  81012. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81013. if (!this._cameraGazer._gazeTracker.material) {
  81014. return;
  81015. }
  81016. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81017. if (this.leftController) {
  81018. this.leftController._gazeTracker.material.emissiveColor = color;
  81019. }
  81020. if (this.rightController) {
  81021. this.rightController._gazeTracker.material.emissiveColor = color;
  81022. }
  81023. };
  81024. /**
  81025. * Exits VR and disposes of the vr experience helper
  81026. */
  81027. VRExperienceHelper.prototype.dispose = function () {
  81028. if (this.isInVRMode) {
  81029. this.exitVR();
  81030. }
  81031. if (this._postProcessMove) {
  81032. this._postProcessMove.dispose();
  81033. }
  81034. if (this._webVRCamera) {
  81035. this._webVRCamera.dispose();
  81036. }
  81037. if (this._vrDeviceOrientationCamera) {
  81038. this._vrDeviceOrientationCamera.dispose();
  81039. }
  81040. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81041. document.body.removeChild(this._btnVR);
  81042. }
  81043. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81044. this._deviceOrientationCamera.dispose();
  81045. }
  81046. if (this._cameraGazer) {
  81047. this._cameraGazer.dispose();
  81048. }
  81049. if (this.leftController) {
  81050. this.leftController.dispose();
  81051. }
  81052. if (this.rightController) {
  81053. this.rightController.dispose();
  81054. }
  81055. if (this._teleportationTarget) {
  81056. this._teleportationTarget.dispose();
  81057. }
  81058. this._floorMeshesCollection = [];
  81059. document.removeEventListener("keydown", this._onKeyDown);
  81060. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81061. window.removeEventListener("resize", this._onResize);
  81062. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81063. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81064. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81065. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81066. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81067. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81068. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81069. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81070. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81071. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81072. this._scene.unregisterBeforeRender(this.beforeRender);
  81073. };
  81074. /**
  81075. * Gets the name of the VRExperienceHelper class
  81076. * @returns "VRExperienceHelper"
  81077. */
  81078. VRExperienceHelper.prototype.getClassName = function () {
  81079. return "VRExperienceHelper";
  81080. };
  81081. return VRExperienceHelper;
  81082. }());
  81083. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81084. })(BABYLON || (BABYLON = {}));
  81085. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81086. // Mainly based on these 2 articles :
  81087. // 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
  81088. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81089. var BABYLON;
  81090. (function (BABYLON) {
  81091. var JoystickAxis;
  81092. (function (JoystickAxis) {
  81093. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81094. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81095. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81096. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81097. var VirtualJoystick = /** @class */ (function () {
  81098. function VirtualJoystick(leftJoystick) {
  81099. var _this = this;
  81100. if (leftJoystick) {
  81101. this._leftJoystick = true;
  81102. }
  81103. else {
  81104. this._leftJoystick = false;
  81105. }
  81106. VirtualJoystick._globalJoystickIndex++;
  81107. // By default left & right arrow keys are moving the X
  81108. // and up & down keys are moving the Y
  81109. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81110. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81111. this.reverseLeftRight = false;
  81112. this.reverseUpDown = false;
  81113. // collections of pointers
  81114. this._touches = new BABYLON.StringDictionary();
  81115. this.deltaPosition = BABYLON.Vector3.Zero();
  81116. this._joystickSensibility = 25;
  81117. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81118. this._onResize = function (evt) {
  81119. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81120. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81121. if (VirtualJoystick.vjCanvas) {
  81122. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81123. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81124. }
  81125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81126. };
  81127. // injecting a canvas element on top of the canvas 3D game
  81128. if (!VirtualJoystick.vjCanvas) {
  81129. window.addEventListener("resize", this._onResize, false);
  81130. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81131. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81132. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81133. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81134. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81135. VirtualJoystick.vjCanvas.style.width = "100%";
  81136. VirtualJoystick.vjCanvas.style.height = "100%";
  81137. VirtualJoystick.vjCanvas.style.position = "absolute";
  81138. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81139. VirtualJoystick.vjCanvas.style.top = "0px";
  81140. VirtualJoystick.vjCanvas.style.left = "0px";
  81141. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81142. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81143. // Support for jQuery PEP polyfill
  81144. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81145. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81146. if (!context) {
  81147. throw new Error("Unable to create canvas for virtual joystick");
  81148. }
  81149. VirtualJoystick.vjCanvasContext = context;
  81150. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81151. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81152. document.body.appendChild(VirtualJoystick.vjCanvas);
  81153. }
  81154. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81155. this.pressed = false;
  81156. // default joystick color
  81157. this._joystickColor = "cyan";
  81158. this._joystickPointerID = -1;
  81159. // current joystick position
  81160. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81161. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81162. // origin joystick position
  81163. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81164. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81165. this._onPointerDownHandlerRef = function (evt) {
  81166. _this._onPointerDown(evt);
  81167. };
  81168. this._onPointerMoveHandlerRef = function (evt) {
  81169. _this._onPointerMove(evt);
  81170. };
  81171. this._onPointerUpHandlerRef = function (evt) {
  81172. _this._onPointerUp(evt);
  81173. };
  81174. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81175. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81176. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81177. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81178. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81179. evt.preventDefault(); // Disables system menu
  81180. }, false);
  81181. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81182. }
  81183. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81184. this._joystickSensibility = newJoystickSensibility;
  81185. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81186. };
  81187. VirtualJoystick.prototype._onPointerDown = function (e) {
  81188. var positionOnScreenCondition;
  81189. e.preventDefault();
  81190. if (this._leftJoystick === true) {
  81191. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81192. }
  81193. else {
  81194. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81195. }
  81196. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81197. // First contact will be dedicated to the virtual joystick
  81198. this._joystickPointerID = e.pointerId;
  81199. this._joystickPointerStartPos.x = e.clientX;
  81200. this._joystickPointerStartPos.y = e.clientY;
  81201. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81202. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81203. this._deltaJoystickVector.x = 0;
  81204. this._deltaJoystickVector.y = 0;
  81205. this.pressed = true;
  81206. this._touches.add(e.pointerId.toString(), e);
  81207. }
  81208. else {
  81209. // You can only trigger the action buttons with a joystick declared
  81210. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81211. this._action();
  81212. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81213. }
  81214. }
  81215. };
  81216. VirtualJoystick.prototype._onPointerMove = function (e) {
  81217. // If the current pointer is the one associated to the joystick (first touch contact)
  81218. if (this._joystickPointerID == e.pointerId) {
  81219. this._joystickPointerPos.x = e.clientX;
  81220. this._joystickPointerPos.y = e.clientY;
  81221. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81222. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81223. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81224. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81225. switch (this._axisTargetedByLeftAndRight) {
  81226. case JoystickAxis.X:
  81227. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81228. break;
  81229. case JoystickAxis.Y:
  81230. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81231. break;
  81232. case JoystickAxis.Z:
  81233. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81234. break;
  81235. }
  81236. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81237. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81238. switch (this._axisTargetedByUpAndDown) {
  81239. case JoystickAxis.X:
  81240. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81241. break;
  81242. case JoystickAxis.Y:
  81243. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81244. break;
  81245. case JoystickAxis.Z:
  81246. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81247. break;
  81248. }
  81249. }
  81250. else {
  81251. var data = this._touches.get(e.pointerId.toString());
  81252. if (data) {
  81253. data.x = e.clientX;
  81254. data.y = e.clientY;
  81255. }
  81256. }
  81257. };
  81258. VirtualJoystick.prototype._onPointerUp = function (e) {
  81259. if (this._joystickPointerID == e.pointerId) {
  81260. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81261. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81262. this._joystickPointerID = -1;
  81263. this.pressed = false;
  81264. }
  81265. else {
  81266. var touch = this._touches.get(e.pointerId.toString());
  81267. if (touch) {
  81268. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81269. }
  81270. }
  81271. this._deltaJoystickVector.x = 0;
  81272. this._deltaJoystickVector.y = 0;
  81273. this._touches.remove(e.pointerId.toString());
  81274. };
  81275. /**
  81276. * Change the color of the virtual joystick
  81277. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81278. */
  81279. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81280. this._joystickColor = newColor;
  81281. };
  81282. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81283. this._action = action;
  81284. };
  81285. // Define which axis you'd like to control for left & right
  81286. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81287. switch (axis) {
  81288. case JoystickAxis.X:
  81289. case JoystickAxis.Y:
  81290. case JoystickAxis.Z:
  81291. this._axisTargetedByLeftAndRight = axis;
  81292. break;
  81293. default:
  81294. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81295. break;
  81296. }
  81297. };
  81298. // Define which axis you'd like to control for up & down
  81299. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81300. switch (axis) {
  81301. case JoystickAxis.X:
  81302. case JoystickAxis.Y:
  81303. case JoystickAxis.Z:
  81304. this._axisTargetedByUpAndDown = axis;
  81305. break;
  81306. default:
  81307. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81308. break;
  81309. }
  81310. };
  81311. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81312. var _this = this;
  81313. if (this.pressed) {
  81314. this._touches.forEach(function (key, touch) {
  81315. if (touch.pointerId === _this._joystickPointerID) {
  81316. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81317. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81318. VirtualJoystick.vjCanvasContext.beginPath();
  81319. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81320. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81321. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81322. VirtualJoystick.vjCanvasContext.stroke();
  81323. VirtualJoystick.vjCanvasContext.closePath();
  81324. VirtualJoystick.vjCanvasContext.beginPath();
  81325. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81326. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81327. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81328. VirtualJoystick.vjCanvasContext.stroke();
  81329. VirtualJoystick.vjCanvasContext.closePath();
  81330. VirtualJoystick.vjCanvasContext.beginPath();
  81331. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81332. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81333. VirtualJoystick.vjCanvasContext.stroke();
  81334. VirtualJoystick.vjCanvasContext.closePath();
  81335. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81336. }
  81337. else {
  81338. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81339. VirtualJoystick.vjCanvasContext.beginPath();
  81340. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81341. VirtualJoystick.vjCanvasContext.beginPath();
  81342. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81343. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81344. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81345. VirtualJoystick.vjCanvasContext.stroke();
  81346. VirtualJoystick.vjCanvasContext.closePath();
  81347. touch.prevX = touch.x;
  81348. touch.prevY = touch.y;
  81349. }
  81350. ;
  81351. });
  81352. }
  81353. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81354. };
  81355. VirtualJoystick.prototype.releaseCanvas = function () {
  81356. if (VirtualJoystick.vjCanvas) {
  81357. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81358. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81359. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81360. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81361. window.removeEventListener("resize", this._onResize);
  81362. document.body.removeChild(VirtualJoystick.vjCanvas);
  81363. VirtualJoystick.vjCanvas = null;
  81364. }
  81365. };
  81366. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81367. VirtualJoystick._globalJoystickIndex = 0;
  81368. return VirtualJoystick;
  81369. }());
  81370. BABYLON.VirtualJoystick = VirtualJoystick;
  81371. })(BABYLON || (BABYLON = {}));
  81372. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81373. var BABYLON;
  81374. (function (BABYLON) {
  81375. // We're mainly based on the logic defined into the FreeCamera code
  81376. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81377. __extends(VirtualJoysticksCamera, _super);
  81378. function VirtualJoysticksCamera(name, position, scene) {
  81379. var _this = _super.call(this, name, position, scene) || this;
  81380. _this.inputs.addVirtualJoystick();
  81381. return _this;
  81382. }
  81383. VirtualJoysticksCamera.prototype.getClassName = function () {
  81384. return "VirtualJoysticksCamera";
  81385. };
  81386. return VirtualJoysticksCamera;
  81387. }(BABYLON.FreeCamera));
  81388. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81389. })(BABYLON || (BABYLON = {}));
  81390. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81391. var BABYLON;
  81392. (function (BABYLON) {
  81393. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81394. function FreeCameraVirtualJoystickInput() {
  81395. }
  81396. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81397. return this._leftjoystick;
  81398. };
  81399. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81400. return this._rightjoystick;
  81401. };
  81402. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81403. if (this._leftjoystick) {
  81404. var camera = this.camera;
  81405. var speed = camera._computeLocalCameraSpeed() * 50;
  81406. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81407. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81408. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81409. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81410. if (!this._leftjoystick.pressed) {
  81411. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81412. }
  81413. if (!this._rightjoystick.pressed) {
  81414. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81415. }
  81416. }
  81417. };
  81418. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81419. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81420. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81421. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81422. this._leftjoystick.setJoystickSensibility(0.15);
  81423. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81424. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81425. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81426. this._rightjoystick.reverseUpDown = true;
  81427. this._rightjoystick.setJoystickSensibility(0.05);
  81428. this._rightjoystick.setJoystickColor("yellow");
  81429. };
  81430. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81431. this._leftjoystick.releaseCanvas();
  81432. this._rightjoystick.releaseCanvas();
  81433. };
  81434. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81435. return "FreeCameraVirtualJoystickInput";
  81436. };
  81437. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81438. return "virtualJoystick";
  81439. };
  81440. return FreeCameraVirtualJoystickInput;
  81441. }());
  81442. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81443. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81444. })(BABYLON || (BABYLON = {}));
  81445. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81446. var BABYLON;
  81447. (function (BABYLON) {
  81448. var SimplificationSettings = /** @class */ (function () {
  81449. function SimplificationSettings(quality, distance, optimizeMesh) {
  81450. this.quality = quality;
  81451. this.distance = distance;
  81452. this.optimizeMesh = optimizeMesh;
  81453. }
  81454. return SimplificationSettings;
  81455. }());
  81456. BABYLON.SimplificationSettings = SimplificationSettings;
  81457. var SimplificationQueue = /** @class */ (function () {
  81458. function SimplificationQueue() {
  81459. this.running = false;
  81460. this._simplificationArray = [];
  81461. }
  81462. SimplificationQueue.prototype.addTask = function (task) {
  81463. this._simplificationArray.push(task);
  81464. };
  81465. SimplificationQueue.prototype.executeNext = function () {
  81466. var task = this._simplificationArray.pop();
  81467. if (task) {
  81468. this.running = true;
  81469. this.runSimplification(task);
  81470. }
  81471. else {
  81472. this.running = false;
  81473. }
  81474. };
  81475. SimplificationQueue.prototype.runSimplification = function (task) {
  81476. var _this = this;
  81477. if (task.parallelProcessing) {
  81478. //parallel simplifier
  81479. task.settings.forEach(function (setting) {
  81480. var simplifier = _this.getSimplifier(task);
  81481. simplifier.simplify(setting, function (newMesh) {
  81482. task.mesh.addLODLevel(setting.distance, newMesh);
  81483. newMesh.isVisible = true;
  81484. //check if it is the last
  81485. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81486. //all done, run the success callback.
  81487. task.successCallback();
  81488. }
  81489. _this.executeNext();
  81490. });
  81491. });
  81492. }
  81493. else {
  81494. //single simplifier.
  81495. var simplifier = this.getSimplifier(task);
  81496. var runDecimation = function (setting, callback) {
  81497. simplifier.simplify(setting, function (newMesh) {
  81498. task.mesh.addLODLevel(setting.distance, newMesh);
  81499. newMesh.isVisible = true;
  81500. //run the next quality level
  81501. callback();
  81502. });
  81503. };
  81504. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81505. runDecimation(task.settings[loop.index], function () {
  81506. loop.executeNext();
  81507. });
  81508. }, function () {
  81509. //execution ended, run the success callback.
  81510. if (task.successCallback) {
  81511. task.successCallback();
  81512. }
  81513. _this.executeNext();
  81514. });
  81515. }
  81516. };
  81517. SimplificationQueue.prototype.getSimplifier = function (task) {
  81518. switch (task.simplificationType) {
  81519. case SimplificationType.QUADRATIC:
  81520. default:
  81521. return new QuadraticErrorSimplification(task.mesh);
  81522. }
  81523. };
  81524. return SimplificationQueue;
  81525. }());
  81526. BABYLON.SimplificationQueue = SimplificationQueue;
  81527. /**
  81528. * The implemented types of simplification.
  81529. * At the moment only Quadratic Error Decimation is implemented.
  81530. */
  81531. var SimplificationType;
  81532. (function (SimplificationType) {
  81533. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81534. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81535. var DecimationTriangle = /** @class */ (function () {
  81536. function DecimationTriangle(vertices) {
  81537. this.vertices = vertices;
  81538. this.error = new Array(4);
  81539. this.deleted = false;
  81540. this.isDirty = false;
  81541. this.deletePending = false;
  81542. this.borderFactor = 0;
  81543. }
  81544. return DecimationTriangle;
  81545. }());
  81546. BABYLON.DecimationTriangle = DecimationTriangle;
  81547. var DecimationVertex = /** @class */ (function () {
  81548. function DecimationVertex(position, id) {
  81549. this.position = position;
  81550. this.id = id;
  81551. this.isBorder = true;
  81552. this.q = new QuadraticMatrix();
  81553. this.triangleCount = 0;
  81554. this.triangleStart = 0;
  81555. this.originalOffsets = [];
  81556. }
  81557. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81558. this.position.copyFrom(newPosition);
  81559. };
  81560. return DecimationVertex;
  81561. }());
  81562. BABYLON.DecimationVertex = DecimationVertex;
  81563. var QuadraticMatrix = /** @class */ (function () {
  81564. function QuadraticMatrix(data) {
  81565. this.data = new Array(10);
  81566. for (var i = 0; i < 10; ++i) {
  81567. if (data && data[i]) {
  81568. this.data[i] = data[i];
  81569. }
  81570. else {
  81571. this.data[i] = 0;
  81572. }
  81573. }
  81574. }
  81575. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81576. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81577. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81578. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81579. return det;
  81580. };
  81581. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81582. for (var i = 0; i < 10; ++i) {
  81583. this.data[i] += matrix.data[i];
  81584. }
  81585. };
  81586. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81587. for (var i = 0; i < 10; ++i) {
  81588. this.data[i] += data[i];
  81589. }
  81590. };
  81591. QuadraticMatrix.prototype.add = function (matrix) {
  81592. var m = new QuadraticMatrix();
  81593. for (var i = 0; i < 10; ++i) {
  81594. m.data[i] = this.data[i] + matrix.data[i];
  81595. }
  81596. return m;
  81597. };
  81598. QuadraticMatrix.FromData = function (a, b, c, d) {
  81599. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81600. };
  81601. //returning an array to avoid garbage collection
  81602. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81603. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81604. };
  81605. return QuadraticMatrix;
  81606. }());
  81607. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81608. var Reference = /** @class */ (function () {
  81609. function Reference(vertexId, triangleId) {
  81610. this.vertexId = vertexId;
  81611. this.triangleId = triangleId;
  81612. }
  81613. return Reference;
  81614. }());
  81615. BABYLON.Reference = Reference;
  81616. /**
  81617. * An implementation of the Quadratic Error simplification algorithm.
  81618. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81619. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81620. * @author RaananW
  81621. */
  81622. var QuadraticErrorSimplification = /** @class */ (function () {
  81623. function QuadraticErrorSimplification(_mesh) {
  81624. this._mesh = _mesh;
  81625. this.syncIterations = 5000;
  81626. this.aggressiveness = 7;
  81627. this.decimationIterations = 100;
  81628. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81629. }
  81630. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81631. var _this = this;
  81632. this.initDecimatedMesh();
  81633. //iterating through the submeshes array, one after the other.
  81634. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81635. _this.initWithMesh(loop.index, function () {
  81636. _this.runDecimation(settings, loop.index, function () {
  81637. loop.executeNext();
  81638. });
  81639. }, settings.optimizeMesh);
  81640. }, function () {
  81641. setTimeout(function () {
  81642. successCallback(_this._reconstructedMesh);
  81643. }, 0);
  81644. });
  81645. };
  81646. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81647. var _this = this;
  81648. var targetCount = ~~(this.triangles.length * settings.quality);
  81649. var deletedTriangles = 0;
  81650. var triangleCount = this.triangles.length;
  81651. var iterationFunction = function (iteration, callback) {
  81652. setTimeout(function () {
  81653. if (iteration % 5 === 0) {
  81654. _this.updateMesh(iteration === 0);
  81655. }
  81656. for (var i = 0; i < _this.triangles.length; ++i) {
  81657. _this.triangles[i].isDirty = false;
  81658. }
  81659. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81660. var trianglesIterator = function (i) {
  81661. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81662. var t = _this.triangles[tIdx];
  81663. if (!t)
  81664. return;
  81665. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81666. return;
  81667. }
  81668. for (var j = 0; j < 3; ++j) {
  81669. if (t.error[j] < threshold) {
  81670. var deleted0 = [];
  81671. var deleted1 = [];
  81672. var v0 = t.vertices[j];
  81673. var v1 = t.vertices[(j + 1) % 3];
  81674. if (v0.isBorder || v1.isBorder)
  81675. continue;
  81676. var p = BABYLON.Vector3.Zero();
  81677. var n = BABYLON.Vector3.Zero();
  81678. var uv = BABYLON.Vector2.Zero();
  81679. var color = new BABYLON.Color4(0, 0, 0, 1);
  81680. _this.calculateError(v0, v1, p, n, uv, color);
  81681. var delTr = new Array();
  81682. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81683. continue;
  81684. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81685. continue;
  81686. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  81687. continue;
  81688. var uniqueArray = new Array();
  81689. delTr.forEach(function (deletedT) {
  81690. if (uniqueArray.indexOf(deletedT) === -1) {
  81691. deletedT.deletePending = true;
  81692. uniqueArray.push(deletedT);
  81693. }
  81694. });
  81695. if (uniqueArray.length % 2 !== 0) {
  81696. continue;
  81697. }
  81698. v0.q = v1.q.add(v0.q);
  81699. v0.updatePosition(p);
  81700. var tStart = _this.references.length;
  81701. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  81702. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  81703. var tCount = _this.references.length - tStart;
  81704. if (tCount <= v0.triangleCount) {
  81705. if (tCount) {
  81706. for (var c = 0; c < tCount; c++) {
  81707. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  81708. }
  81709. }
  81710. }
  81711. else {
  81712. v0.triangleStart = tStart;
  81713. }
  81714. v0.triangleCount = tCount;
  81715. break;
  81716. }
  81717. }
  81718. };
  81719. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  81720. }, 0);
  81721. };
  81722. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  81723. if (triangleCount - deletedTriangles <= targetCount)
  81724. loop.breakLoop();
  81725. else {
  81726. iterationFunction(loop.index, function () {
  81727. loop.executeNext();
  81728. });
  81729. }
  81730. }, function () {
  81731. setTimeout(function () {
  81732. //reconstruct this part of the mesh
  81733. _this.reconstructMesh(submeshIndex);
  81734. successCallback();
  81735. }, 0);
  81736. });
  81737. };
  81738. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  81739. var _this = this;
  81740. this.vertices = [];
  81741. this.triangles = [];
  81742. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81743. var indices = this._mesh.getIndices();
  81744. var submesh = this._mesh.subMeshes[submeshIndex];
  81745. var findInVertices = function (positionToSearch) {
  81746. if (optimizeMesh) {
  81747. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  81748. if (_this.vertices[ii].position.equals(positionToSearch)) {
  81749. return _this.vertices[ii];
  81750. }
  81751. }
  81752. }
  81753. return null;
  81754. };
  81755. var vertexReferences = [];
  81756. var vertexInit = function (i) {
  81757. if (!positionData) {
  81758. return;
  81759. }
  81760. var offset = i + submesh.verticesStart;
  81761. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  81762. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  81763. vertex.originalOffsets.push(offset);
  81764. if (vertex.id === _this.vertices.length) {
  81765. _this.vertices.push(vertex);
  81766. }
  81767. vertexReferences.push(vertex.id);
  81768. };
  81769. //var totalVertices = mesh.getTotalVertices();
  81770. var totalVertices = submesh.verticesCount;
  81771. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  81772. var indicesInit = function (i) {
  81773. if (!indices) {
  81774. return;
  81775. }
  81776. var offset = (submesh.indexStart / 3) + i;
  81777. var pos = (offset * 3);
  81778. var i0 = indices[pos + 0];
  81779. var i1 = indices[pos + 1];
  81780. var i2 = indices[pos + 2];
  81781. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  81782. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  81783. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  81784. var triangle = new DecimationTriangle([v0, v1, v2]);
  81785. triangle.originalOffset = pos;
  81786. _this.triangles.push(triangle);
  81787. };
  81788. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  81789. _this.init(callback);
  81790. });
  81791. });
  81792. };
  81793. QuadraticErrorSimplification.prototype.init = function (callback) {
  81794. var _this = this;
  81795. var triangleInit1 = function (i) {
  81796. var t = _this.triangles[i];
  81797. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  81798. for (var j = 0; j < 3; j++) {
  81799. 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))));
  81800. }
  81801. };
  81802. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  81803. var triangleInit2 = function (i) {
  81804. var t = _this.triangles[i];
  81805. for (var j = 0; j < 3; ++j) {
  81806. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  81807. }
  81808. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81809. };
  81810. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  81811. callback();
  81812. });
  81813. });
  81814. };
  81815. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  81816. var newTriangles = [];
  81817. var i;
  81818. for (i = 0; i < this.vertices.length; ++i) {
  81819. this.vertices[i].triangleCount = 0;
  81820. }
  81821. var t;
  81822. var j;
  81823. for (i = 0; i < this.triangles.length; ++i) {
  81824. if (!this.triangles[i].deleted) {
  81825. t = this.triangles[i];
  81826. for (j = 0; j < 3; ++j) {
  81827. t.vertices[j].triangleCount = 1;
  81828. }
  81829. newTriangles.push(t);
  81830. }
  81831. }
  81832. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  81833. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  81834. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  81835. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  81836. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  81837. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81838. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  81839. var vertexCount = 0;
  81840. for (i = 0; i < this.vertices.length; ++i) {
  81841. var vertex = this.vertices[i];
  81842. vertex.id = vertexCount;
  81843. if (vertex.triangleCount) {
  81844. vertex.originalOffsets.forEach(function (originalOffset) {
  81845. if (!normalData) {
  81846. return;
  81847. }
  81848. newPositionData.push(vertex.position.x);
  81849. newPositionData.push(vertex.position.y);
  81850. newPositionData.push(vertex.position.z);
  81851. newNormalData.push(normalData[originalOffset * 3]);
  81852. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  81853. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  81854. if (uvs && uvs.length) {
  81855. newUVsData.push(uvs[(originalOffset * 2)]);
  81856. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  81857. }
  81858. else if (colorsData && colorsData.length) {
  81859. newColorsData.push(colorsData[(originalOffset * 4)]);
  81860. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  81861. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  81862. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  81863. }
  81864. ++vertexCount;
  81865. });
  81866. }
  81867. }
  81868. var startingIndex = this._reconstructedMesh.getTotalIndices();
  81869. var startingVertex = this._reconstructedMesh.getTotalVertices();
  81870. var submeshesArray = this._reconstructedMesh.subMeshes;
  81871. this._reconstructedMesh.subMeshes = [];
  81872. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  81873. var originalIndices = this._mesh.getIndices();
  81874. for (i = 0; i < newTriangles.length; ++i) {
  81875. t = newTriangles[i]; //now get the new referencing point for each vertex
  81876. [0, 1, 2].forEach(function (idx) {
  81877. var id = originalIndices[t.originalOffset + idx];
  81878. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  81879. if (offset < 0)
  81880. offset = 0;
  81881. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  81882. });
  81883. }
  81884. //overwriting the old vertex buffers and indices.
  81885. this._reconstructedMesh.setIndices(newIndicesArray);
  81886. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  81887. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  81888. if (newUVsData.length > 0)
  81889. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  81890. if (newColorsData.length > 0)
  81891. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  81892. //create submesh
  81893. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  81894. if (submeshIndex > 0) {
  81895. this._reconstructedMesh.subMeshes = [];
  81896. submeshesArray.forEach(function (submesh) {
  81897. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  81898. });
  81899. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  81900. }
  81901. };
  81902. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  81903. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  81904. this._reconstructedMesh.material = this._mesh.material;
  81905. this._reconstructedMesh.parent = this._mesh.parent;
  81906. this._reconstructedMesh.isVisible = false;
  81907. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81908. };
  81909. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81910. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81911. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81912. if (t.deleted)
  81913. continue;
  81914. var s = this.references[vertex1.triangleStart + i].vertexId;
  81915. var v1 = t.vertices[(s + 1) % 3];
  81916. var v2 = t.vertices[(s + 2) % 3];
  81917. if ((v1 === vertex2 || v2 === vertex2)) {
  81918. deletedArray[i] = true;
  81919. delTr.push(t);
  81920. continue;
  81921. }
  81922. var d1 = v1.position.subtract(point);
  81923. d1 = d1.normalize();
  81924. var d2 = v2.position.subtract(point);
  81925. d2 = d2.normalize();
  81926. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81927. return true;
  81928. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81929. deletedArray[i] = false;
  81930. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81931. return true;
  81932. }
  81933. return false;
  81934. };
  81935. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81936. var newDeleted = deletedTriangles;
  81937. for (var i = 0; i < vertex.triangleCount; ++i) {
  81938. var ref = this.references[vertex.triangleStart + i];
  81939. var t = this.triangles[ref.triangleId];
  81940. if (t.deleted)
  81941. continue;
  81942. if (deletedArray[i] && t.deletePending) {
  81943. t.deleted = true;
  81944. newDeleted++;
  81945. continue;
  81946. }
  81947. t.vertices[ref.vertexId] = origVertex;
  81948. t.isDirty = true;
  81949. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81950. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81951. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81952. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81953. this.references.push(ref);
  81954. }
  81955. return newDeleted;
  81956. };
  81957. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81958. for (var i = 0; i < this.vertices.length; ++i) {
  81959. var vCount = [];
  81960. var vId = [];
  81961. var v = this.vertices[i];
  81962. var j;
  81963. for (j = 0; j < v.triangleCount; ++j) {
  81964. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81965. for (var ii = 0; ii < 3; ii++) {
  81966. var ofs = 0;
  81967. var vv = triangle.vertices[ii];
  81968. while (ofs < vCount.length) {
  81969. if (vId[ofs] === vv.id)
  81970. break;
  81971. ++ofs;
  81972. }
  81973. if (ofs === vCount.length) {
  81974. vCount.push(1);
  81975. vId.push(vv.id);
  81976. }
  81977. else {
  81978. vCount[ofs]++;
  81979. }
  81980. }
  81981. }
  81982. for (j = 0; j < vCount.length; ++j) {
  81983. if (vCount[j] === 1) {
  81984. this.vertices[vId[j]].isBorder = true;
  81985. }
  81986. else {
  81987. this.vertices[vId[j]].isBorder = false;
  81988. }
  81989. }
  81990. }
  81991. };
  81992. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81993. if (identifyBorders === void 0) { identifyBorders = false; }
  81994. var i;
  81995. if (!identifyBorders) {
  81996. var newTrianglesVector = [];
  81997. for (i = 0; i < this.triangles.length; ++i) {
  81998. if (!this.triangles[i].deleted) {
  81999. newTrianglesVector.push(this.triangles[i]);
  82000. }
  82001. }
  82002. this.triangles = newTrianglesVector;
  82003. }
  82004. for (i = 0; i < this.vertices.length; ++i) {
  82005. this.vertices[i].triangleCount = 0;
  82006. this.vertices[i].triangleStart = 0;
  82007. }
  82008. var t;
  82009. var j;
  82010. var v;
  82011. for (i = 0; i < this.triangles.length; ++i) {
  82012. t = this.triangles[i];
  82013. for (j = 0; j < 3; ++j) {
  82014. v = t.vertices[j];
  82015. v.triangleCount++;
  82016. }
  82017. }
  82018. var tStart = 0;
  82019. for (i = 0; i < this.vertices.length; ++i) {
  82020. this.vertices[i].triangleStart = tStart;
  82021. tStart += this.vertices[i].triangleCount;
  82022. this.vertices[i].triangleCount = 0;
  82023. }
  82024. var newReferences = new Array(this.triangles.length * 3);
  82025. for (i = 0; i < this.triangles.length; ++i) {
  82026. t = this.triangles[i];
  82027. for (j = 0; j < 3; ++j) {
  82028. v = t.vertices[j];
  82029. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82030. v.triangleCount++;
  82031. }
  82032. }
  82033. this.references = newReferences;
  82034. if (identifyBorders) {
  82035. this.identifyBorder();
  82036. }
  82037. };
  82038. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82039. var x = point.x;
  82040. var y = point.y;
  82041. var z = point.z;
  82042. 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
  82043. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82044. };
  82045. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82046. var q = vertex1.q.add(vertex2.q);
  82047. var border = vertex1.isBorder && vertex2.isBorder;
  82048. var error = 0;
  82049. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82050. if (qDet !== 0 && !border) {
  82051. if (!pointResult) {
  82052. pointResult = BABYLON.Vector3.Zero();
  82053. }
  82054. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82055. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82056. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82057. error = this.vertexError(q, pointResult);
  82058. }
  82059. else {
  82060. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82061. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82062. var error1 = this.vertexError(q, vertex1.position);
  82063. var error2 = this.vertexError(q, vertex2.position);
  82064. var error3 = this.vertexError(q, p3);
  82065. error = Math.min(error1, error2, error3);
  82066. if (error === error1) {
  82067. if (pointResult) {
  82068. pointResult.copyFrom(vertex1.position);
  82069. }
  82070. }
  82071. else if (error === error2) {
  82072. if (pointResult) {
  82073. pointResult.copyFrom(vertex2.position);
  82074. }
  82075. }
  82076. else {
  82077. if (pointResult) {
  82078. pointResult.copyFrom(p3);
  82079. }
  82080. }
  82081. }
  82082. return error;
  82083. };
  82084. return QuadraticErrorSimplification;
  82085. }());
  82086. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82087. })(BABYLON || (BABYLON = {}));
  82088. //# sourceMappingURL=babylon.meshSimplification.js.map
  82089. var BABYLON;
  82090. (function (BABYLON) {
  82091. var MeshLODLevel = /** @class */ (function () {
  82092. function MeshLODLevel(distance, mesh) {
  82093. this.distance = distance;
  82094. this.mesh = mesh;
  82095. }
  82096. return MeshLODLevel;
  82097. }());
  82098. BABYLON.MeshLODLevel = MeshLODLevel;
  82099. })(BABYLON || (BABYLON = {}));
  82100. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82101. var BABYLON;
  82102. (function (BABYLON) {
  82103. /**
  82104. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82105. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82106. */
  82107. var SceneOptimization = /** @class */ (function () {
  82108. /**
  82109. * Creates the SceneOptimization object
  82110. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82111. * @param desc defines the description associated with the optimization
  82112. */
  82113. function SceneOptimization(
  82114. /**
  82115. * Defines the priority of this optimization (0 by default which means first in the list)
  82116. */
  82117. priority) {
  82118. if (priority === void 0) { priority = 0; }
  82119. this.priority = priority;
  82120. }
  82121. /**
  82122. * Gets a string describing the action executed by the current optimization
  82123. * @returns description string
  82124. */
  82125. SceneOptimization.prototype.getDescription = function () {
  82126. return "";
  82127. };
  82128. /**
  82129. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82130. * @param scene defines the current scene where to apply this optimization
  82131. * @param optimizer defines the current optimizer
  82132. * @returns true if everything that can be done was applied
  82133. */
  82134. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82135. return true;
  82136. };
  82137. ;
  82138. return SceneOptimization;
  82139. }());
  82140. BABYLON.SceneOptimization = SceneOptimization;
  82141. /**
  82142. * Defines an optimization used to reduce the size of render target textures
  82143. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82144. */
  82145. var TextureOptimization = /** @class */ (function (_super) {
  82146. __extends(TextureOptimization, _super);
  82147. /**
  82148. * Creates the TextureOptimization object
  82149. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82150. * @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
  82151. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82152. */
  82153. function TextureOptimization(
  82154. /**
  82155. * Defines the priority of this optimization (0 by default which means first in the list)
  82156. */
  82157. priority,
  82158. /**
  82159. * 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
  82160. */
  82161. maximumSize,
  82162. /**
  82163. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82164. */
  82165. step) {
  82166. if (priority === void 0) { priority = 0; }
  82167. if (maximumSize === void 0) { maximumSize = 1024; }
  82168. if (step === void 0) { step = 0.5; }
  82169. var _this = _super.call(this, priority) || this;
  82170. _this.priority = priority;
  82171. _this.maximumSize = maximumSize;
  82172. _this.step = step;
  82173. return _this;
  82174. }
  82175. /**
  82176. * Gets a string describing the action executed by the current optimization
  82177. * @returns description string
  82178. */
  82179. TextureOptimization.prototype.getDescription = function () {
  82180. return "Reducing render target texture size to " + this.maximumSize;
  82181. };
  82182. /**
  82183. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82184. * @param scene defines the current scene where to apply this optimization
  82185. * @param optimizer defines the current optimizer
  82186. * @returns true if everything that can be done was applied
  82187. */
  82188. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82189. var allDone = true;
  82190. for (var index = 0; index < scene.textures.length; index++) {
  82191. var texture = scene.textures[index];
  82192. if (!texture.canRescale || texture.getContext) {
  82193. continue;
  82194. }
  82195. var currentSize = texture.getSize();
  82196. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82197. if (maxDimension > this.maximumSize) {
  82198. texture.scale(this.step);
  82199. allDone = false;
  82200. }
  82201. }
  82202. return allDone;
  82203. };
  82204. return TextureOptimization;
  82205. }(SceneOptimization));
  82206. BABYLON.TextureOptimization = TextureOptimization;
  82207. /**
  82208. * Defines an optimization used to increase or decrease the rendering resolution
  82209. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82210. */
  82211. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82212. __extends(HardwareScalingOptimization, _super);
  82213. /**
  82214. * Creates the HardwareScalingOptimization object
  82215. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82216. * @param maximumScale defines the maximum scale to use (2 by default)
  82217. * @param step defines the step to use between two passes (0.5 by default)
  82218. */
  82219. function HardwareScalingOptimization(
  82220. /**
  82221. * Defines the priority of this optimization (0 by default which means first in the list)
  82222. */
  82223. priority,
  82224. /**
  82225. * Defines the maximum scale to use (2 by default)
  82226. */
  82227. maximumScale,
  82228. /**
  82229. * Defines the step to use between two passes (0.5 by default)
  82230. */
  82231. step) {
  82232. if (priority === void 0) { priority = 0; }
  82233. if (maximumScale === void 0) { maximumScale = 2; }
  82234. if (step === void 0) { step = 0.25; }
  82235. var _this = _super.call(this, priority) || this;
  82236. _this.priority = priority;
  82237. _this.maximumScale = maximumScale;
  82238. _this.step = step;
  82239. _this._currentScale = -1;
  82240. _this._directionOffset = 1;
  82241. return _this;
  82242. }
  82243. /**
  82244. * Gets a string describing the action executed by the current optimization
  82245. * @return description string
  82246. */
  82247. HardwareScalingOptimization.prototype.getDescription = function () {
  82248. return "Setting hardware scaling level to " + this._currentScale;
  82249. };
  82250. /**
  82251. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82252. * @param scene defines the current scene where to apply this optimization
  82253. * @param optimizer defines the current optimizer
  82254. * @returns true if everything that can be done was applied
  82255. */
  82256. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82257. if (this._currentScale === -1) {
  82258. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82259. if (this._currentScale > this.maximumScale) {
  82260. this._directionOffset = -1;
  82261. }
  82262. }
  82263. this._currentScale += this._directionOffset * this.step;
  82264. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82265. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82266. };
  82267. ;
  82268. return HardwareScalingOptimization;
  82269. }(SceneOptimization));
  82270. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82271. /**
  82272. * Defines an optimization used to remove shadows
  82273. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82274. */
  82275. var ShadowsOptimization = /** @class */ (function (_super) {
  82276. __extends(ShadowsOptimization, _super);
  82277. function ShadowsOptimization() {
  82278. return _super !== null && _super.apply(this, arguments) || this;
  82279. }
  82280. /**
  82281. * Gets a string describing the action executed by the current optimization
  82282. * @return description string
  82283. */
  82284. ShadowsOptimization.prototype.getDescription = function () {
  82285. return "Turning shadows on/off";
  82286. };
  82287. /**
  82288. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82289. * @param scene defines the current scene where to apply this optimization
  82290. * @param optimizer defines the current optimizer
  82291. * @returns true if everything that can be done was applied
  82292. */
  82293. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82294. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82295. return true;
  82296. };
  82297. ;
  82298. return ShadowsOptimization;
  82299. }(SceneOptimization));
  82300. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82301. /**
  82302. * Defines an optimization used to turn post-processes off
  82303. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82304. */
  82305. var PostProcessesOptimization = /** @class */ (function (_super) {
  82306. __extends(PostProcessesOptimization, _super);
  82307. function PostProcessesOptimization() {
  82308. return _super !== null && _super.apply(this, arguments) || this;
  82309. }
  82310. /**
  82311. * Gets a string describing the action executed by the current optimization
  82312. * @return description string
  82313. */
  82314. PostProcessesOptimization.prototype.getDescription = function () {
  82315. return "Turning post-processes on/off";
  82316. };
  82317. /**
  82318. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82319. * @param scene defines the current scene where to apply this optimization
  82320. * @param optimizer defines the current optimizer
  82321. * @returns true if everything that can be done was applied
  82322. */
  82323. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82324. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82325. return true;
  82326. };
  82327. ;
  82328. return PostProcessesOptimization;
  82329. }(SceneOptimization));
  82330. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82331. /**
  82332. * Defines an optimization used to turn lens flares off
  82333. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82334. */
  82335. var LensFlaresOptimization = /** @class */ (function (_super) {
  82336. __extends(LensFlaresOptimization, _super);
  82337. function LensFlaresOptimization() {
  82338. return _super !== null && _super.apply(this, arguments) || this;
  82339. }
  82340. /**
  82341. * Gets a string describing the action executed by the current optimization
  82342. * @return description string
  82343. */
  82344. LensFlaresOptimization.prototype.getDescription = function () {
  82345. return "Turning lens flares on/off";
  82346. };
  82347. /**
  82348. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82349. * @param scene defines the current scene where to apply this optimization
  82350. * @param optimizer defines the current optimizer
  82351. * @returns true if everything that can be done was applied
  82352. */
  82353. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82354. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82355. return true;
  82356. };
  82357. ;
  82358. return LensFlaresOptimization;
  82359. }(SceneOptimization));
  82360. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82361. /**
  82362. * Defines an optimization based on user defined callback.
  82363. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82364. */
  82365. var CustomOptimization = /** @class */ (function (_super) {
  82366. __extends(CustomOptimization, _super);
  82367. function CustomOptimization() {
  82368. return _super !== null && _super.apply(this, arguments) || this;
  82369. }
  82370. /**
  82371. * Gets a string describing the action executed by the current optimization
  82372. * @returns description string
  82373. */
  82374. CustomOptimization.prototype.getDescription = function () {
  82375. if (this.onGetDescription) {
  82376. return this.onGetDescription();
  82377. }
  82378. return "Running user defined callback";
  82379. };
  82380. /**
  82381. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82382. * @param scene defines the current scene where to apply this optimization
  82383. * @param optimizer defines the current optimizer
  82384. * @returns true if everything that can be done was applied
  82385. */
  82386. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82387. if (this.onApply) {
  82388. return this.onApply(scene, optimizer);
  82389. }
  82390. return true;
  82391. };
  82392. ;
  82393. return CustomOptimization;
  82394. }(SceneOptimization));
  82395. BABYLON.CustomOptimization = CustomOptimization;
  82396. /**
  82397. * Defines an optimization used to turn particles off
  82398. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82399. */
  82400. var ParticlesOptimization = /** @class */ (function (_super) {
  82401. __extends(ParticlesOptimization, _super);
  82402. function ParticlesOptimization() {
  82403. return _super !== null && _super.apply(this, arguments) || this;
  82404. }
  82405. /**
  82406. * Gets a string describing the action executed by the current optimization
  82407. * @return description string
  82408. */
  82409. ParticlesOptimization.prototype.getDescription = function () {
  82410. return "Turning particles on/off";
  82411. };
  82412. /**
  82413. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82414. * @param scene defines the current scene where to apply this optimization
  82415. * @param optimizer defines the current optimizer
  82416. * @returns true if everything that can be done was applied
  82417. */
  82418. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82419. scene.particlesEnabled = optimizer.isInImprovementMode;
  82420. return true;
  82421. };
  82422. ;
  82423. return ParticlesOptimization;
  82424. }(SceneOptimization));
  82425. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82426. /**
  82427. * Defines an optimization used to turn render targets off
  82428. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82429. */
  82430. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82431. __extends(RenderTargetsOptimization, _super);
  82432. function RenderTargetsOptimization() {
  82433. return _super !== null && _super.apply(this, arguments) || this;
  82434. }
  82435. /**
  82436. * Gets a string describing the action executed by the current optimization
  82437. * @return description string
  82438. */
  82439. RenderTargetsOptimization.prototype.getDescription = function () {
  82440. return "Turning render targets off";
  82441. };
  82442. /**
  82443. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82444. * @param scene defines the current scene where to apply this optimization
  82445. * @param optimizer defines the current optimizer
  82446. * @returns true if everything that can be done was applied
  82447. */
  82448. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82449. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82450. return true;
  82451. };
  82452. ;
  82453. return RenderTargetsOptimization;
  82454. }(SceneOptimization));
  82455. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82456. /**
  82457. * Defines an optimization used to merge meshes with compatible materials
  82458. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82459. */
  82460. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82461. __extends(MergeMeshesOptimization, _super);
  82462. function MergeMeshesOptimization() {
  82463. var _this = _super !== null && _super.apply(this, arguments) || this;
  82464. _this._canBeMerged = function (abstractMesh) {
  82465. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82466. return false;
  82467. }
  82468. var mesh = abstractMesh;
  82469. if (!mesh.isVisible || !mesh.isEnabled()) {
  82470. return false;
  82471. }
  82472. if (mesh.instances.length > 0) {
  82473. return false;
  82474. }
  82475. if (mesh.skeleton || mesh.hasLODLevels) {
  82476. return false;
  82477. }
  82478. if (mesh.parent) {
  82479. return false;
  82480. }
  82481. return true;
  82482. };
  82483. return _this;
  82484. }
  82485. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82486. /**
  82487. * Gets or sets a boolean which defines if optimization octree has to be updated
  82488. */
  82489. get: function () {
  82490. return MergeMeshesOptimization._UpdateSelectionTree;
  82491. },
  82492. /**
  82493. * Gets or sets a boolean which defines if optimization octree has to be updated
  82494. */
  82495. set: function (value) {
  82496. MergeMeshesOptimization._UpdateSelectionTree = value;
  82497. },
  82498. enumerable: true,
  82499. configurable: true
  82500. });
  82501. /**
  82502. * Gets a string describing the action executed by the current optimization
  82503. * @return description string
  82504. */
  82505. MergeMeshesOptimization.prototype.getDescription = function () {
  82506. return "Merging similar meshes together";
  82507. };
  82508. /**
  82509. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82510. * @param scene defines the current scene where to apply this optimization
  82511. * @param optimizer defines the current optimizer
  82512. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82513. * @returns true if everything that can be done was applied
  82514. */
  82515. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82516. var globalPool = scene.meshes.slice(0);
  82517. var globalLength = globalPool.length;
  82518. for (var index = 0; index < globalLength; index++) {
  82519. var currentPool = new Array();
  82520. var current = globalPool[index];
  82521. // Checks
  82522. if (!this._canBeMerged(current)) {
  82523. continue;
  82524. }
  82525. currentPool.push(current);
  82526. // Find compatible meshes
  82527. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82528. var otherMesh = globalPool[subIndex];
  82529. if (!this._canBeMerged(otherMesh)) {
  82530. continue;
  82531. }
  82532. if (otherMesh.material !== current.material) {
  82533. continue;
  82534. }
  82535. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82536. continue;
  82537. }
  82538. currentPool.push(otherMesh);
  82539. globalLength--;
  82540. globalPool.splice(subIndex, 1);
  82541. subIndex--;
  82542. }
  82543. if (currentPool.length < 2) {
  82544. continue;
  82545. }
  82546. // Merge meshes
  82547. BABYLON.Mesh.MergeMeshes(currentPool);
  82548. }
  82549. if (updateSelectionTree != undefined) {
  82550. if (updateSelectionTree) {
  82551. scene.createOrUpdateSelectionOctree();
  82552. }
  82553. }
  82554. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82555. scene.createOrUpdateSelectionOctree();
  82556. }
  82557. return true;
  82558. };
  82559. ;
  82560. MergeMeshesOptimization._UpdateSelectionTree = false;
  82561. return MergeMeshesOptimization;
  82562. }(SceneOptimization));
  82563. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82564. /**
  82565. * Defines a list of options used by SceneOptimizer
  82566. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82567. */
  82568. var SceneOptimizerOptions = /** @class */ (function () {
  82569. /**
  82570. * Creates a new list of options used by SceneOptimizer
  82571. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82572. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82573. */
  82574. function SceneOptimizerOptions(
  82575. /**
  82576. * Defines the target frame rate to reach (60 by default)
  82577. */
  82578. targetFrameRate,
  82579. /**
  82580. * Defines the interval between two checkes (2000ms by default)
  82581. */
  82582. trackerDuration) {
  82583. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82584. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82585. this.targetFrameRate = targetFrameRate;
  82586. this.trackerDuration = trackerDuration;
  82587. /**
  82588. * Gets the list of optimizations to apply
  82589. */
  82590. this.optimizations = new Array();
  82591. }
  82592. /**
  82593. * Add a new optimization
  82594. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82595. * @returns the current SceneOptimizerOptions
  82596. */
  82597. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82598. this.optimizations.push(optimization);
  82599. return this;
  82600. };
  82601. /**
  82602. * Add a new custom optimization
  82603. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82604. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82605. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82606. * @returns the current SceneOptimizerOptions
  82607. */
  82608. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82609. if (priority === void 0) { priority = 0; }
  82610. var optimization = new CustomOptimization(priority);
  82611. optimization.onApply = onApply;
  82612. optimization.onGetDescription = onGetDescription;
  82613. this.optimizations.push(optimization);
  82614. return this;
  82615. };
  82616. /**
  82617. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82618. * @param targetFrameRate defines the target frame rate (60 by default)
  82619. * @returns a SceneOptimizerOptions object
  82620. */
  82621. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82622. var result = new SceneOptimizerOptions(targetFrameRate);
  82623. var priority = 0;
  82624. result.addOptimization(new MergeMeshesOptimization(priority));
  82625. result.addOptimization(new ShadowsOptimization(priority));
  82626. result.addOptimization(new LensFlaresOptimization(priority));
  82627. // Next priority
  82628. priority++;
  82629. result.addOptimization(new PostProcessesOptimization(priority));
  82630. result.addOptimization(new ParticlesOptimization(priority));
  82631. // Next priority
  82632. priority++;
  82633. result.addOptimization(new TextureOptimization(priority, 1024));
  82634. return result;
  82635. };
  82636. /**
  82637. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82638. * @param targetFrameRate defines the target frame rate (60 by default)
  82639. * @returns a SceneOptimizerOptions object
  82640. */
  82641. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82642. var result = new SceneOptimizerOptions(targetFrameRate);
  82643. var priority = 0;
  82644. result.addOptimization(new MergeMeshesOptimization(priority));
  82645. result.addOptimization(new ShadowsOptimization(priority));
  82646. result.addOptimization(new LensFlaresOptimization(priority));
  82647. // Next priority
  82648. priority++;
  82649. result.addOptimization(new PostProcessesOptimization(priority));
  82650. result.addOptimization(new ParticlesOptimization(priority));
  82651. // Next priority
  82652. priority++;
  82653. result.addOptimization(new TextureOptimization(priority, 512));
  82654. // Next priority
  82655. priority++;
  82656. result.addOptimization(new RenderTargetsOptimization(priority));
  82657. // Next priority
  82658. priority++;
  82659. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82660. return result;
  82661. };
  82662. /**
  82663. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82664. * @param targetFrameRate defines the target frame rate (60 by default)
  82665. * @returns a SceneOptimizerOptions object
  82666. */
  82667. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82668. var result = new SceneOptimizerOptions(targetFrameRate);
  82669. var priority = 0;
  82670. result.addOptimization(new MergeMeshesOptimization(priority));
  82671. result.addOptimization(new ShadowsOptimization(priority));
  82672. result.addOptimization(new LensFlaresOptimization(priority));
  82673. // Next priority
  82674. priority++;
  82675. result.addOptimization(new PostProcessesOptimization(priority));
  82676. result.addOptimization(new ParticlesOptimization(priority));
  82677. // Next priority
  82678. priority++;
  82679. result.addOptimization(new TextureOptimization(priority, 256));
  82680. // Next priority
  82681. priority++;
  82682. result.addOptimization(new RenderTargetsOptimization(priority));
  82683. // Next priority
  82684. priority++;
  82685. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82686. return result;
  82687. };
  82688. return SceneOptimizerOptions;
  82689. }());
  82690. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  82691. /**
  82692. * Class used to run optimizations in order to reach a target frame rate
  82693. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82694. */
  82695. var SceneOptimizer = /** @class */ (function () {
  82696. /**
  82697. * Creates a new SceneOptimizer
  82698. * @param scene defines the scene to work on
  82699. * @param options defines the options to use with the SceneOptimizer
  82700. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  82701. * @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)
  82702. */
  82703. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  82704. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  82705. if (improvementMode === void 0) { improvementMode = false; }
  82706. var _this = this;
  82707. this._isRunning = false;
  82708. this._currentPriorityLevel = 0;
  82709. this._targetFrameRate = 60;
  82710. this._trackerDuration = 2000;
  82711. this._currentFrameRate = 0;
  82712. this._improvementMode = false;
  82713. /**
  82714. * Defines an observable called when the optimizer reaches the target frame rate
  82715. */
  82716. this.onSuccessObservable = new BABYLON.Observable();
  82717. /**
  82718. * Defines an observable called when the optimizer enables an optimization
  82719. */
  82720. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  82721. /**
  82722. * Defines an observable called when the optimizer is not able to reach the target frame rate
  82723. */
  82724. this.onFailureObservable = new BABYLON.Observable();
  82725. if (!options) {
  82726. this._options = new SceneOptimizerOptions();
  82727. }
  82728. else {
  82729. this._options = options;
  82730. }
  82731. if (this._options.targetFrameRate) {
  82732. this._targetFrameRate = this._options.targetFrameRate;
  82733. }
  82734. if (this._options.trackerDuration) {
  82735. this._trackerDuration = this._options.trackerDuration;
  82736. }
  82737. if (autoGeneratePriorities) {
  82738. var priority = 0;
  82739. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  82740. var optim = _a[_i];
  82741. optim.priority = priority++;
  82742. }
  82743. }
  82744. this._improvementMode = improvementMode;
  82745. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82746. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  82747. _this._sceneDisposeObserver = null;
  82748. _this.dispose();
  82749. });
  82750. }
  82751. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  82752. /**
  82753. * Gets a boolean indicating if the optimizer is in improvement mode
  82754. */
  82755. get: function () {
  82756. return this._improvementMode;
  82757. },
  82758. enumerable: true,
  82759. configurable: true
  82760. });
  82761. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  82762. /**
  82763. * Gets the current priority level (0 at start)
  82764. */
  82765. get: function () {
  82766. return this._currentPriorityLevel;
  82767. },
  82768. enumerable: true,
  82769. configurable: true
  82770. });
  82771. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  82772. /**
  82773. * Gets the current frame rate checked by the SceneOptimizer
  82774. */
  82775. get: function () {
  82776. return this._currentFrameRate;
  82777. },
  82778. enumerable: true,
  82779. configurable: true
  82780. });
  82781. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  82782. /**
  82783. * Gets or sets the current target frame rate (60 by default)
  82784. */
  82785. get: function () {
  82786. return this._targetFrameRate;
  82787. },
  82788. /**
  82789. * Gets or sets the current target frame rate (60 by default)
  82790. */
  82791. set: function (value) {
  82792. this._targetFrameRate = value;
  82793. },
  82794. enumerable: true,
  82795. configurable: true
  82796. });
  82797. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  82798. /**
  82799. * Gets or sets the current interval between two checks (every 2000ms by default)
  82800. */
  82801. get: function () {
  82802. return this._trackerDuration;
  82803. },
  82804. /**
  82805. * Gets or sets the current interval between two checks (every 2000ms by default)
  82806. */
  82807. set: function (value) {
  82808. this._trackerDuration = value;
  82809. },
  82810. enumerable: true,
  82811. configurable: true
  82812. });
  82813. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  82814. /**
  82815. * Gets the list of active optimizations
  82816. */
  82817. get: function () {
  82818. return this._options.optimizations;
  82819. },
  82820. enumerable: true,
  82821. configurable: true
  82822. });
  82823. /**
  82824. * Stops the current optimizer
  82825. */
  82826. SceneOptimizer.prototype.stop = function () {
  82827. this._isRunning = false;
  82828. };
  82829. /**
  82830. * Reset the optimizer to initial step (current priority level = 0)
  82831. */
  82832. SceneOptimizer.prototype.reset = function () {
  82833. this._currentPriorityLevel = 0;
  82834. };
  82835. /**
  82836. * Start the optimizer. By default it will try to reach a specific framerate
  82837. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  82838. */
  82839. SceneOptimizer.prototype.start = function () {
  82840. var _this = this;
  82841. if (this._isRunning) {
  82842. return;
  82843. }
  82844. this._isRunning = true;
  82845. // Let's wait for the scene to be ready before running our check
  82846. this._scene.executeWhenReady(function () {
  82847. setTimeout(function () {
  82848. _this._checkCurrentState();
  82849. }, _this._trackerDuration);
  82850. });
  82851. };
  82852. SceneOptimizer.prototype._checkCurrentState = function () {
  82853. var _this = this;
  82854. if (!this._isRunning) {
  82855. return;
  82856. }
  82857. var scene = this._scene;
  82858. var options = this._options;
  82859. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  82860. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  82861. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  82862. this._isRunning = false;
  82863. this.onSuccessObservable.notifyObservers(this);
  82864. return;
  82865. }
  82866. // Apply current level of optimizations
  82867. var allDone = true;
  82868. var noOptimizationApplied = true;
  82869. for (var index = 0; index < options.optimizations.length; index++) {
  82870. var optimization = options.optimizations[index];
  82871. if (optimization.priority === this._currentPriorityLevel) {
  82872. noOptimizationApplied = false;
  82873. allDone = allDone && optimization.apply(scene, this);
  82874. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  82875. }
  82876. }
  82877. // If no optimization was applied, this is a failure :(
  82878. if (noOptimizationApplied) {
  82879. this._isRunning = false;
  82880. this.onFailureObservable.notifyObservers(this);
  82881. return;
  82882. }
  82883. // If all optimizations were done, move to next level
  82884. if (allDone) {
  82885. this._currentPriorityLevel++;
  82886. }
  82887. // Let's the system running for a specific amount of time before checking FPS
  82888. scene.executeWhenReady(function () {
  82889. setTimeout(function () {
  82890. _this._checkCurrentState();
  82891. }, _this._trackerDuration);
  82892. });
  82893. };
  82894. /**
  82895. * Release all resources
  82896. */
  82897. SceneOptimizer.prototype.dispose = function () {
  82898. this.stop();
  82899. this.onSuccessObservable.clear();
  82900. this.onFailureObservable.clear();
  82901. this.onNewOptimizationAppliedObservable.clear();
  82902. if (this._sceneDisposeObserver) {
  82903. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  82904. }
  82905. };
  82906. /**
  82907. * Helper function to create a SceneOptimizer with one single line of code
  82908. * @param scene defines the scene to work on
  82909. * @param options defines the options to use with the SceneOptimizer
  82910. * @param onSuccess defines a callback to call on success
  82911. * @param onFailure defines a callback to call on failure
  82912. * @returns the new SceneOptimizer object
  82913. */
  82914. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82915. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82916. if (onSuccess) {
  82917. optimizer.onSuccessObservable.add(function () {
  82918. onSuccess();
  82919. });
  82920. }
  82921. if (onFailure) {
  82922. optimizer.onFailureObservable.add(function () {
  82923. onFailure();
  82924. });
  82925. }
  82926. optimizer.start();
  82927. return optimizer;
  82928. };
  82929. return SceneOptimizer;
  82930. }());
  82931. BABYLON.SceneOptimizer = SceneOptimizer;
  82932. })(BABYLON || (BABYLON = {}));
  82933. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82934. var BABYLON;
  82935. (function (BABYLON) {
  82936. var OutlineRenderer = /** @class */ (function () {
  82937. function OutlineRenderer(scene) {
  82938. this.zOffset = 1;
  82939. this._scene = scene;
  82940. }
  82941. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82942. var _this = this;
  82943. if (useOverlay === void 0) { useOverlay = false; }
  82944. var scene = this._scene;
  82945. var engine = this._scene.getEngine();
  82946. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82947. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82948. return;
  82949. }
  82950. var mesh = subMesh.getRenderingMesh();
  82951. var material = subMesh.getMaterial();
  82952. if (!material || !scene.activeCamera) {
  82953. return;
  82954. }
  82955. engine.enableEffect(this._effect);
  82956. // Logarithmic depth
  82957. if (material.useLogarithmicDepth) {
  82958. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82959. }
  82960. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82961. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82962. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82963. // Bones
  82964. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82965. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82966. }
  82967. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82968. // Alpha test
  82969. if (material && material.needAlphaTesting()) {
  82970. var alphaTexture = material.getAlphaTestTexture();
  82971. if (alphaTexture) {
  82972. this._effect.setTexture("diffuseSampler", alphaTexture);
  82973. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82974. }
  82975. }
  82976. engine.setZOffset(-this.zOffset);
  82977. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82978. engine.setZOffset(0);
  82979. };
  82980. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82981. var defines = [];
  82982. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82983. var mesh = subMesh.getMesh();
  82984. var material = subMesh.getMaterial();
  82985. if (material) {
  82986. // Alpha test
  82987. if (material.needAlphaTesting()) {
  82988. defines.push("#define ALPHATEST");
  82989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82990. attribs.push(BABYLON.VertexBuffer.UVKind);
  82991. defines.push("#define UV1");
  82992. }
  82993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82994. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82995. defines.push("#define UV2");
  82996. }
  82997. }
  82998. //Logarithmic depth
  82999. if (material.useLogarithmicDepth) {
  83000. defines.push("#define LOGARITHMICDEPTH");
  83001. }
  83002. }
  83003. // Bones
  83004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83007. if (mesh.numBoneInfluencers > 4) {
  83008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83010. }
  83011. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83012. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83013. }
  83014. else {
  83015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83016. }
  83017. // Instances
  83018. if (useInstances) {
  83019. defines.push("#define INSTANCES");
  83020. attribs.push("world0");
  83021. attribs.push("world1");
  83022. attribs.push("world2");
  83023. attribs.push("world3");
  83024. }
  83025. // Get correct effect
  83026. var join = defines.join("\n");
  83027. if (this._cachedDefines !== join) {
  83028. this._cachedDefines = join;
  83029. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83030. }
  83031. return this._effect.isReady();
  83032. };
  83033. return OutlineRenderer;
  83034. }());
  83035. BABYLON.OutlineRenderer = OutlineRenderer;
  83036. })(BABYLON || (BABYLON = {}));
  83037. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83038. var BABYLON;
  83039. (function (BABYLON) {
  83040. var FaceAdjacencies = /** @class */ (function () {
  83041. function FaceAdjacencies() {
  83042. this.edges = new Array();
  83043. this.edgesConnectedCount = 0;
  83044. }
  83045. return FaceAdjacencies;
  83046. }());
  83047. var EdgesRenderer = /** @class */ (function () {
  83048. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83049. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83050. if (epsilon === void 0) { epsilon = 0.95; }
  83051. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83052. this.edgesWidthScalerForOrthographic = 1000.0;
  83053. this.edgesWidthScalerForPerspective = 50.0;
  83054. this._linesPositions = new Array();
  83055. this._linesNormals = new Array();
  83056. this._linesIndices = new Array();
  83057. this._buffers = {};
  83058. this._checkVerticesInsteadOfIndices = false;
  83059. this._source = source;
  83060. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83061. this._epsilon = epsilon;
  83062. this._prepareRessources();
  83063. this._generateEdgesLines();
  83064. }
  83065. EdgesRenderer.prototype._prepareRessources = function () {
  83066. if (this._lineShader) {
  83067. return;
  83068. }
  83069. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83070. attributes: ["position", "normal"],
  83071. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83072. });
  83073. this._lineShader.disableDepthWrite = true;
  83074. this._lineShader.backFaceCulling = false;
  83075. };
  83076. EdgesRenderer.prototype._rebuild = function () {
  83077. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83078. if (buffer) {
  83079. buffer._rebuild();
  83080. }
  83081. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83082. if (buffer) {
  83083. buffer._rebuild();
  83084. }
  83085. var scene = this._source.getScene();
  83086. var engine = scene.getEngine();
  83087. this._ib = engine.createIndexBuffer(this._linesIndices);
  83088. };
  83089. EdgesRenderer.prototype.dispose = function () {
  83090. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83091. if (buffer) {
  83092. buffer.dispose();
  83093. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83094. }
  83095. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83096. if (buffer) {
  83097. buffer.dispose();
  83098. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83099. }
  83100. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83101. this._lineShader.dispose();
  83102. };
  83103. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83104. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83105. return 0;
  83106. }
  83107. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83108. return 1;
  83109. }
  83110. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83111. return 2;
  83112. }
  83113. return -1;
  83114. };
  83115. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83116. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83117. return 0;
  83118. }
  83119. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83120. return 1;
  83121. }
  83122. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83123. return 2;
  83124. }
  83125. return -1;
  83126. };
  83127. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83128. var needToCreateLine;
  83129. if (edge === undefined) {
  83130. needToCreateLine = true;
  83131. }
  83132. else {
  83133. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83134. needToCreateLine = dotProduct < this._epsilon;
  83135. }
  83136. if (needToCreateLine) {
  83137. var offset = this._linesPositions.length / 3;
  83138. var normal = p0.subtract(p1);
  83139. normal.normalize();
  83140. // Positions
  83141. this._linesPositions.push(p0.x);
  83142. this._linesPositions.push(p0.y);
  83143. this._linesPositions.push(p0.z);
  83144. this._linesPositions.push(p0.x);
  83145. this._linesPositions.push(p0.y);
  83146. this._linesPositions.push(p0.z);
  83147. this._linesPositions.push(p1.x);
  83148. this._linesPositions.push(p1.y);
  83149. this._linesPositions.push(p1.z);
  83150. this._linesPositions.push(p1.x);
  83151. this._linesPositions.push(p1.y);
  83152. this._linesPositions.push(p1.z);
  83153. // Normals
  83154. this._linesNormals.push(p1.x);
  83155. this._linesNormals.push(p1.y);
  83156. this._linesNormals.push(p1.z);
  83157. this._linesNormals.push(-1);
  83158. this._linesNormals.push(p1.x);
  83159. this._linesNormals.push(p1.y);
  83160. this._linesNormals.push(p1.z);
  83161. this._linesNormals.push(1);
  83162. this._linesNormals.push(p0.x);
  83163. this._linesNormals.push(p0.y);
  83164. this._linesNormals.push(p0.z);
  83165. this._linesNormals.push(-1);
  83166. this._linesNormals.push(p0.x);
  83167. this._linesNormals.push(p0.y);
  83168. this._linesNormals.push(p0.z);
  83169. this._linesNormals.push(1);
  83170. // Indices
  83171. this._linesIndices.push(offset);
  83172. this._linesIndices.push(offset + 1);
  83173. this._linesIndices.push(offset + 2);
  83174. this._linesIndices.push(offset);
  83175. this._linesIndices.push(offset + 2);
  83176. this._linesIndices.push(offset + 3);
  83177. }
  83178. };
  83179. EdgesRenderer.prototype._generateEdgesLines = function () {
  83180. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83181. var indices = this._source.getIndices();
  83182. if (!indices || !positions) {
  83183. return;
  83184. }
  83185. // First let's find adjacencies
  83186. var adjacencies = new Array();
  83187. var faceNormals = new Array();
  83188. var index;
  83189. var faceAdjacencies;
  83190. // Prepare faces
  83191. for (index = 0; index < indices.length; index += 3) {
  83192. faceAdjacencies = new FaceAdjacencies();
  83193. var p0Index = indices[index];
  83194. var p1Index = indices[index + 1];
  83195. var p2Index = indices[index + 2];
  83196. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83197. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83198. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83199. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83200. faceNormal.normalize();
  83201. faceNormals.push(faceNormal);
  83202. adjacencies.push(faceAdjacencies);
  83203. }
  83204. // Scan
  83205. for (index = 0; index < adjacencies.length; index++) {
  83206. faceAdjacencies = adjacencies[index];
  83207. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83208. var otherFaceAdjacencies = adjacencies[otherIndex];
  83209. if (faceAdjacencies.edgesConnectedCount === 3) {
  83210. break;
  83211. }
  83212. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83213. continue;
  83214. }
  83215. var otherP0 = indices[otherIndex * 3];
  83216. var otherP1 = indices[otherIndex * 3 + 1];
  83217. var otherP2 = indices[otherIndex * 3 + 2];
  83218. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83219. var otherEdgeIndex = 0;
  83220. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83221. continue;
  83222. }
  83223. switch (edgeIndex) {
  83224. case 0:
  83225. if (this._checkVerticesInsteadOfIndices) {
  83226. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83227. }
  83228. else {
  83229. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83230. }
  83231. break;
  83232. case 1:
  83233. if (this._checkVerticesInsteadOfIndices) {
  83234. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83235. }
  83236. else {
  83237. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83238. }
  83239. break;
  83240. case 2:
  83241. if (this._checkVerticesInsteadOfIndices) {
  83242. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83243. }
  83244. else {
  83245. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83246. }
  83247. break;
  83248. }
  83249. if (otherEdgeIndex === -1) {
  83250. continue;
  83251. }
  83252. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83253. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83254. faceAdjacencies.edgesConnectedCount++;
  83255. otherFaceAdjacencies.edgesConnectedCount++;
  83256. if (faceAdjacencies.edgesConnectedCount === 3) {
  83257. break;
  83258. }
  83259. }
  83260. }
  83261. }
  83262. // Create lines
  83263. for (index = 0; index < adjacencies.length; index++) {
  83264. // 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
  83265. var current = adjacencies[index];
  83266. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83267. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83268. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83269. }
  83270. // Merge into a single mesh
  83271. var engine = this._source.getScene().getEngine();
  83272. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83273. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83274. this._ib = engine.createIndexBuffer(this._linesIndices);
  83275. this._indicesCount = this._linesIndices.length;
  83276. };
  83277. EdgesRenderer.prototype.render = function () {
  83278. var scene = this._source.getScene();
  83279. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83280. return;
  83281. }
  83282. var engine = scene.getEngine();
  83283. this._lineShader._preBind();
  83284. // VBOs
  83285. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83286. scene.resetCachedMaterial();
  83287. this._lineShader.setColor4("color", this._source.edgesColor);
  83288. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83289. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83290. }
  83291. else {
  83292. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83293. }
  83294. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83295. this._lineShader.bind(this._source.getWorldMatrix());
  83296. // Draw order
  83297. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83298. this._lineShader.unbind();
  83299. engine.setDepthWrite(true);
  83300. };
  83301. return EdgesRenderer;
  83302. }());
  83303. BABYLON.EdgesRenderer = EdgesRenderer;
  83304. })(BABYLON || (BABYLON = {}));
  83305. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83306. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83307. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83308. s = arguments[i];
  83309. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83310. t[p] = s[p];
  83311. }
  83312. return t;
  83313. };
  83314. var BABYLON;
  83315. (function (BABYLON) {
  83316. /**
  83317. * The effect layer Helps adding post process effect blended with the main pass.
  83318. *
  83319. * This can be for instance use to generate glow or higlight effects on the scene.
  83320. *
  83321. * The effect layer class can not be used directly and is intented to inherited from to be
  83322. * customized per effects.
  83323. */
  83324. var EffectLayer = /** @class */ (function () {
  83325. /**
  83326. * Instantiates a new effect Layer and references it in the scene.
  83327. * @param name The name of the layer
  83328. * @param scene The scene to use the layer in
  83329. */
  83330. function EffectLayer(
  83331. /** The Friendly of the effect in the scene */
  83332. name, scene) {
  83333. this.name = name;
  83334. this._vertexBuffers = {};
  83335. this._maxSize = 0;
  83336. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83337. this._shouldRender = true;
  83338. this._postProcesses = [];
  83339. this._textures = [];
  83340. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83341. /**
  83342. * The clear color of the texture used to generate the glow map.
  83343. */
  83344. this.neutralColor = new BABYLON.Color4();
  83345. /**
  83346. * Specifies wether the highlight layer is enabled or not.
  83347. */
  83348. this.isEnabled = true;
  83349. /**
  83350. * An event triggered when the effect layer has been disposed.
  83351. */
  83352. this.onDisposeObservable = new BABYLON.Observable();
  83353. /**
  83354. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83355. */
  83356. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83357. /**
  83358. * An event triggered when the generated texture is being merged in the scene.
  83359. */
  83360. this.onBeforeComposeObservable = new BABYLON.Observable();
  83361. /**
  83362. * An event triggered when the generated texture has been merged in the scene.
  83363. */
  83364. this.onAfterComposeObservable = new BABYLON.Observable();
  83365. /**
  83366. * An event triggered when the efffect layer changes its size.
  83367. */
  83368. this.onSizeChangedObservable = new BABYLON.Observable();
  83369. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83370. this._engine = scene.getEngine();
  83371. this._maxSize = this._engine.getCaps().maxTextureSize;
  83372. this._scene.effectLayers.push(this);
  83373. // Generate Buffers
  83374. this._generateIndexBuffer();
  83375. this._genrateVertexBuffer();
  83376. }
  83377. Object.defineProperty(EffectLayer.prototype, "camera", {
  83378. /**
  83379. * Gets the camera attached to the layer.
  83380. */
  83381. get: function () {
  83382. return this._effectLayerOptions.camera;
  83383. },
  83384. enumerable: true,
  83385. configurable: true
  83386. });
  83387. /**
  83388. * Initializes the effect layer with the required options.
  83389. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83390. */
  83391. EffectLayer.prototype._init = function (options) {
  83392. // Adapt options
  83393. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83394. this._setMainTextureSize();
  83395. this._createMainTexture();
  83396. this._createTextureAndPostProcesses();
  83397. this._mergeEffect = this._createMergeEffect();
  83398. };
  83399. /**
  83400. * Generates the index buffer of the full screen quad blending to the main canvas.
  83401. */
  83402. EffectLayer.prototype._generateIndexBuffer = function () {
  83403. // Indices
  83404. var indices = [];
  83405. indices.push(0);
  83406. indices.push(1);
  83407. indices.push(2);
  83408. indices.push(0);
  83409. indices.push(2);
  83410. indices.push(3);
  83411. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83412. };
  83413. /**
  83414. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83415. */
  83416. EffectLayer.prototype._genrateVertexBuffer = function () {
  83417. // VBO
  83418. var vertices = [];
  83419. vertices.push(1, 1);
  83420. vertices.push(-1, 1);
  83421. vertices.push(-1, -1);
  83422. vertices.push(1, -1);
  83423. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83425. };
  83426. /**
  83427. * Sets the main texture desired size which is the closest power of two
  83428. * of the engine canvas size.
  83429. */
  83430. EffectLayer.prototype._setMainTextureSize = function () {
  83431. if (this._effectLayerOptions.mainTextureFixedSize) {
  83432. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83433. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83434. }
  83435. else {
  83436. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83437. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83438. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83439. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83440. }
  83441. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83442. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83443. };
  83444. /**
  83445. * Creates the main texture for the effect layer.
  83446. */
  83447. EffectLayer.prototype._createMainTexture = function () {
  83448. var _this = this;
  83449. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83450. width: this._mainTextureDesiredSize.width,
  83451. height: this._mainTextureDesiredSize.height
  83452. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83453. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83454. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83455. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83456. this._mainTexture.anisotropicFilteringLevel = 1;
  83457. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83458. this._mainTexture.renderParticles = false;
  83459. this._mainTexture.renderList = null;
  83460. this._mainTexture.ignoreCameraViewport = true;
  83461. // Custom render function
  83462. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83463. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83464. var index;
  83465. var engine = _this._scene.getEngine();
  83466. if (depthOnlySubMeshes.length) {
  83467. engine.setColorWrite(false);
  83468. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83469. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83470. }
  83471. engine.setColorWrite(true);
  83472. }
  83473. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83474. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83475. }
  83476. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83477. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83478. }
  83479. for (index = 0; index < transparentSubMeshes.length; index++) {
  83480. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83481. }
  83482. };
  83483. this._mainTexture.onClearObservable.add(function (engine) {
  83484. engine.clear(_this.neutralColor, true, true, true);
  83485. });
  83486. };
  83487. /**
  83488. * Checks for the readiness of the element composing the layer.
  83489. * @param subMesh the mesh to check for
  83490. * @param useInstances specify wether or not to use instances to render the mesh
  83491. * @param emissiveTexture the associated emissive texture used to generate the glow
  83492. * @return true if ready otherwise, false
  83493. */
  83494. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83495. var material = subMesh.getMaterial();
  83496. if (!material) {
  83497. return false;
  83498. }
  83499. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83500. return false;
  83501. }
  83502. var defines = [];
  83503. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83504. var mesh = subMesh.getMesh();
  83505. var uv1 = false;
  83506. var uv2 = false;
  83507. // Alpha test
  83508. if (material && material.needAlphaTesting()) {
  83509. var alphaTexture = material.getAlphaTestTexture();
  83510. if (alphaTexture) {
  83511. defines.push("#define ALPHATEST");
  83512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83513. alphaTexture.coordinatesIndex === 1) {
  83514. defines.push("#define DIFFUSEUV2");
  83515. uv2 = true;
  83516. }
  83517. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83518. defines.push("#define DIFFUSEUV1");
  83519. uv1 = true;
  83520. }
  83521. }
  83522. }
  83523. // Emissive
  83524. if (emissiveTexture) {
  83525. defines.push("#define EMISSIVE");
  83526. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83527. emissiveTexture.coordinatesIndex === 1) {
  83528. defines.push("#define EMISSIVEUV2");
  83529. uv2 = true;
  83530. }
  83531. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83532. defines.push("#define EMISSIVEUV1");
  83533. uv1 = true;
  83534. }
  83535. }
  83536. if (uv1) {
  83537. attribs.push(BABYLON.VertexBuffer.UVKind);
  83538. defines.push("#define UV1");
  83539. }
  83540. if (uv2) {
  83541. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83542. defines.push("#define UV2");
  83543. }
  83544. // Bones
  83545. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83546. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83547. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83548. if (mesh.numBoneInfluencers > 4) {
  83549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83551. }
  83552. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83553. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83554. }
  83555. else {
  83556. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83557. }
  83558. // Instances
  83559. if (useInstances) {
  83560. defines.push("#define INSTANCES");
  83561. attribs.push("world0");
  83562. attribs.push("world1");
  83563. attribs.push("world2");
  83564. attribs.push("world3");
  83565. }
  83566. // Get correct effect
  83567. var join = defines.join("\n");
  83568. if (this._cachedDefines !== join) {
  83569. this._cachedDefines = join;
  83570. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83571. }
  83572. return this._effectLayerMapGenerationEffect.isReady();
  83573. };
  83574. /**
  83575. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83576. */
  83577. EffectLayer.prototype.render = function () {
  83578. var currentEffect = this._mergeEffect;
  83579. // Check
  83580. if (!currentEffect.isReady())
  83581. return;
  83582. for (var i = 0; i < this._postProcesses.length; i++) {
  83583. if (!this._postProcesses[i].isReady()) {
  83584. return;
  83585. }
  83586. }
  83587. var engine = this._scene.getEngine();
  83588. this.onBeforeComposeObservable.notifyObservers(this);
  83589. // Render
  83590. engine.enableEffect(currentEffect);
  83591. engine.setState(false);
  83592. // VBOs
  83593. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83594. // Cache
  83595. var previousAlphaMode = engine.getAlphaMode();
  83596. // Go Blend.
  83597. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83598. // Blends the map on the main canvas.
  83599. this._internalRender(currentEffect);
  83600. // Restore Alpha
  83601. engine.setAlphaMode(previousAlphaMode);
  83602. this.onAfterComposeObservable.notifyObservers(this);
  83603. // Handle size changes.
  83604. var size = this._mainTexture.getSize();
  83605. this._setMainTextureSize();
  83606. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83607. // Recreate RTT and post processes on size change.
  83608. this.onSizeChangedObservable.notifyObservers(this);
  83609. this._disposeTextureAndPostProcesses();
  83610. this._createMainTexture();
  83611. this._createTextureAndPostProcesses();
  83612. }
  83613. };
  83614. /**
  83615. * Determine if a given mesh will be used in the current effect.
  83616. * @param mesh mesh to test
  83617. * @returns true if the mesh will be used
  83618. */
  83619. EffectLayer.prototype.hasMesh = function (mesh) {
  83620. return true;
  83621. };
  83622. /**
  83623. * Returns true if the layer contains information to display, otherwise false.
  83624. * @returns true if the glow layer should be rendered
  83625. */
  83626. EffectLayer.prototype.shouldRender = function () {
  83627. return this.isEnabled && this._shouldRender;
  83628. };
  83629. /**
  83630. * Returns true if the mesh should render, otherwise false.
  83631. * @param mesh The mesh to render
  83632. * @returns true if it should render otherwise false
  83633. */
  83634. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83635. return true;
  83636. };
  83637. /**
  83638. * Returns true if the mesh should render, otherwise false.
  83639. * @param mesh The mesh to render
  83640. * @returns true if it should render otherwise false
  83641. */
  83642. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83643. return true;
  83644. };
  83645. /**
  83646. * Renders the submesh passed in parameter to the generation map.
  83647. */
  83648. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83649. var _this = this;
  83650. if (!this.shouldRender()) {
  83651. return;
  83652. }
  83653. var material = subMesh.getMaterial();
  83654. var mesh = subMesh.getRenderingMesh();
  83655. var scene = this._scene;
  83656. var engine = scene.getEngine();
  83657. if (!material) {
  83658. return;
  83659. }
  83660. // Do not block in blend mode.
  83661. if (material.needAlphaBlendingForMesh(mesh)) {
  83662. return;
  83663. }
  83664. // Culling
  83665. engine.setState(material.backFaceCulling);
  83666. // Managing instances
  83667. var batch = mesh._getInstancesRenderList(subMesh._id);
  83668. if (batch.mustReturn) {
  83669. return;
  83670. }
  83671. // Early Exit per mesh
  83672. if (!this._shouldRenderMesh(mesh)) {
  83673. return;
  83674. }
  83675. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83676. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83677. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83678. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83679. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83680. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83681. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83682. // Alpha test
  83683. if (material && material.needAlphaTesting()) {
  83684. var alphaTexture = material.getAlphaTestTexture();
  83685. if (alphaTexture) {
  83686. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  83687. var textureMatrix = alphaTexture.getTextureMatrix();
  83688. if (textureMatrix) {
  83689. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  83690. }
  83691. }
  83692. }
  83693. // Glow emissive only
  83694. if (this._emissiveTextureAndColor.texture) {
  83695. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  83696. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  83697. }
  83698. // Bones
  83699. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83700. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83701. }
  83702. // Draw
  83703. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  83704. }
  83705. else {
  83706. // Need to reset refresh rate of the shadowMap
  83707. this._mainTexture.resetRefreshCounter();
  83708. }
  83709. };
  83710. /**
  83711. * Rebuild the required buffers.
  83712. * @ignore Internal use only.
  83713. */
  83714. EffectLayer.prototype._rebuild = function () {
  83715. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83716. if (vb) {
  83717. vb._rebuild();
  83718. }
  83719. this._generateIndexBuffer();
  83720. };
  83721. /**
  83722. * Dispose only the render target textures and post process.
  83723. */
  83724. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  83725. this._mainTexture.dispose();
  83726. for (var i = 0; i < this._postProcesses.length; i++) {
  83727. if (this._postProcesses[i]) {
  83728. this._postProcesses[i].dispose();
  83729. }
  83730. }
  83731. this._postProcesses = [];
  83732. for (var i = 0; i < this._textures.length; i++) {
  83733. if (this._textures[i]) {
  83734. this._textures[i].dispose();
  83735. }
  83736. }
  83737. this._textures = [];
  83738. };
  83739. /**
  83740. * Dispose the highlight layer and free resources.
  83741. */
  83742. EffectLayer.prototype.dispose = function () {
  83743. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83744. if (vertexBuffer) {
  83745. vertexBuffer.dispose();
  83746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83747. }
  83748. if (this._indexBuffer) {
  83749. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83750. this._indexBuffer = null;
  83751. }
  83752. // Clean textures and post processes
  83753. this._disposeTextureAndPostProcesses();
  83754. // Remove from scene
  83755. var index = this._scene.effectLayers.indexOf(this, 0);
  83756. if (index > -1) {
  83757. this._scene.effectLayers.splice(index, 1);
  83758. }
  83759. // Callback
  83760. this.onDisposeObservable.notifyObservers(this);
  83761. this.onDisposeObservable.clear();
  83762. this.onBeforeRenderMainTextureObservable.clear();
  83763. this.onBeforeComposeObservable.clear();
  83764. this.onAfterComposeObservable.clear();
  83765. this.onSizeChangedObservable.clear();
  83766. };
  83767. return EffectLayer;
  83768. }());
  83769. BABYLON.EffectLayer = EffectLayer;
  83770. })(BABYLON || (BABYLON = {}));
  83771. //# sourceMappingURL=babylon.effectLayer.js.map
  83772. var BABYLON;
  83773. (function (BABYLON) {
  83774. /**
  83775. * Special Glow Blur post process only blurring the alpha channel
  83776. * It enforces keeping the most luminous color in the color channel.
  83777. */
  83778. var GlowBlurPostProcess = /** @class */ (function (_super) {
  83779. __extends(GlowBlurPostProcess, _super);
  83780. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  83781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83782. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  83783. _this.direction = direction;
  83784. _this.kernel = kernel;
  83785. _this.onApplyObservable.add(function (effect) {
  83786. effect.setFloat2("screenSize", _this.width, _this.height);
  83787. effect.setVector2("direction", _this.direction);
  83788. effect.setFloat("blurWidth", _this.kernel);
  83789. });
  83790. return _this;
  83791. }
  83792. return GlowBlurPostProcess;
  83793. }(BABYLON.PostProcess));
  83794. /**
  83795. * The highlight layer Helps adding a glow effect around a mesh.
  83796. *
  83797. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83798. * glowy meshes to your scene.
  83799. *
  83800. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  83801. */
  83802. var HighlightLayer = /** @class */ (function (_super) {
  83803. __extends(HighlightLayer, _super);
  83804. /**
  83805. * Instantiates a new highlight Layer and references it to the scene..
  83806. * @param name The name of the layer
  83807. * @param scene The scene to use the layer in
  83808. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  83809. */
  83810. function HighlightLayer(name, scene, options) {
  83811. var _this = _super.call(this, name, scene) || this;
  83812. _this.name = name;
  83813. /**
  83814. * Specifies whether or not the inner glow is ACTIVE in the layer.
  83815. */
  83816. _this.innerGlow = true;
  83817. /**
  83818. * Specifies whether or not the outer glow is ACTIVE in the layer.
  83819. */
  83820. _this.outerGlow = true;
  83821. /**
  83822. * An event triggered when the highlight layer is being blurred.
  83823. */
  83824. _this.onBeforeBlurObservable = new BABYLON.Observable();
  83825. /**
  83826. * An event triggered when the highlight layer has been blurred.
  83827. */
  83828. _this.onAfterBlurObservable = new BABYLON.Observable();
  83829. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  83830. _this._meshes = {};
  83831. _this._excludedMeshes = {};
  83832. _this.neutralColor = HighlightLayer.NeutralColor;
  83833. // Warn on stencil
  83834. if (!_this._engine.isStencilEnable) {
  83835. 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 }");
  83836. }
  83837. // Adapt options
  83838. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83839. // Initialize the layer
  83840. _this._init({
  83841. alphaBlendingMode: _this._options.alphaBlendingMode,
  83842. camera: _this._options.camera,
  83843. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83844. mainTextureRatio: _this._options.mainTextureRatio
  83845. });
  83846. // Do not render as long as no meshes have been added
  83847. _this._shouldRender = false;
  83848. return _this;
  83849. }
  83850. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  83851. /**
  83852. * Gets the horizontal size of the blur.
  83853. */
  83854. get: function () {
  83855. return this._horizontalBlurPostprocess.kernel;
  83856. },
  83857. /**
  83858. * Specifies the horizontal size of the blur.
  83859. */
  83860. set: function (value) {
  83861. this._horizontalBlurPostprocess.kernel = value;
  83862. },
  83863. enumerable: true,
  83864. configurable: true
  83865. });
  83866. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  83867. /**
  83868. * Gets the vertical size of the blur.
  83869. */
  83870. get: function () {
  83871. return this._verticalBlurPostprocess.kernel;
  83872. },
  83873. /**
  83874. * Specifies the vertical size of the blur.
  83875. */
  83876. set: function (value) {
  83877. this._verticalBlurPostprocess.kernel = value;
  83878. },
  83879. enumerable: true,
  83880. configurable: true
  83881. });
  83882. /**
  83883. * Get the effect name of the layer.
  83884. * @return The effect name
  83885. */
  83886. HighlightLayer.prototype.getEffectName = function () {
  83887. return HighlightLayer.EffectName;
  83888. };
  83889. /**
  83890. * Create the merge effect. This is the shader use to blit the information back
  83891. * to the main canvas at the end of the scene rendering.
  83892. */
  83893. HighlightLayer.prototype._createMergeEffect = function () {
  83894. // Effect
  83895. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  83896. };
  83897. /**
  83898. * Creates the render target textures and post processes used in the highlight layer.
  83899. */
  83900. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  83901. var _this = this;
  83902. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  83903. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  83904. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83905. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83906. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  83907. width: blurTextureWidth,
  83908. height: blurTextureHeight
  83909. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83910. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83911. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83912. this._blurTexture.anisotropicFilteringLevel = 16;
  83913. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83914. this._blurTexture.renderParticles = false;
  83915. this._blurTexture.ignoreCameraViewport = true;
  83916. this._textures = [this._blurTexture];
  83917. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83918. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83919. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83920. effect.setTexture("textureSampler", _this._mainTexture);
  83921. });
  83922. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83923. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83924. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83925. });
  83926. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83927. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83928. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83929. });
  83930. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83931. }
  83932. else {
  83933. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83934. width: blurTextureWidth,
  83935. height: blurTextureHeight
  83936. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83937. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83938. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83939. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83940. effect.setTexture("textureSampler", _this._mainTexture);
  83941. });
  83942. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83943. width: blurTextureWidth,
  83944. height: blurTextureHeight
  83945. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83946. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83947. }
  83948. this._mainTexture.onAfterUnbindObservable.add(function () {
  83949. _this.onBeforeBlurObservable.notifyObservers(_this);
  83950. var internalTexture = _this._blurTexture.getInternalTexture();
  83951. if (internalTexture) {
  83952. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83953. }
  83954. _this.onAfterBlurObservable.notifyObservers(_this);
  83955. });
  83956. // Prevent autoClear.
  83957. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83958. };
  83959. /**
  83960. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83961. */
  83962. HighlightLayer.prototype.needStencil = function () {
  83963. return true;
  83964. };
  83965. /**
  83966. * Checks for the readiness of the element composing the layer.
  83967. * @param subMesh the mesh to check for
  83968. * @param useInstances specify wether or not to use instances to render the mesh
  83969. * @param emissiveTexture the associated emissive texture used to generate the glow
  83970. * @return true if ready otherwise, false
  83971. */
  83972. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83973. var material = subMesh.getMaterial();
  83974. var mesh = subMesh.getRenderingMesh();
  83975. if (!material || !mesh || !this._meshes) {
  83976. return false;
  83977. }
  83978. var emissiveTexture = null;
  83979. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83980. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83981. emissiveTexture = material.emissiveTexture;
  83982. }
  83983. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83984. };
  83985. /**
  83986. * Implementation specific of rendering the generating effect on the main canvas.
  83987. * @param effect The effect used to render through
  83988. */
  83989. HighlightLayer.prototype._internalRender = function (effect) {
  83990. // Texture
  83991. effect.setTexture("textureSampler", this._blurTexture);
  83992. // Cache
  83993. var engine = this._engine;
  83994. var previousStencilBuffer = engine.getStencilBuffer();
  83995. var previousStencilFunction = engine.getStencilFunction();
  83996. var previousStencilMask = engine.getStencilMask();
  83997. var previousStencilOperationPass = engine.getStencilOperationPass();
  83998. var previousStencilOperationFail = engine.getStencilOperationFail();
  83999. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84000. var previousStencilReference = engine.getStencilFunctionReference();
  84001. // Stencil operations
  84002. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84003. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84004. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84005. // Draw order
  84006. engine.setStencilMask(0x00);
  84007. engine.setStencilBuffer(true);
  84008. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84009. // 2 passes inner outer
  84010. if (this.outerGlow) {
  84011. effect.setFloat("offset", 0);
  84012. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84013. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84014. }
  84015. if (this.innerGlow) {
  84016. effect.setFloat("offset", 1);
  84017. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84018. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84019. }
  84020. // Restore Cache
  84021. engine.setStencilFunction(previousStencilFunction);
  84022. engine.setStencilMask(previousStencilMask);
  84023. engine.setStencilBuffer(previousStencilBuffer);
  84024. engine.setStencilOperationPass(previousStencilOperationPass);
  84025. engine.setStencilOperationFail(previousStencilOperationFail);
  84026. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84027. engine.setStencilFunctionReference(previousStencilReference);
  84028. };
  84029. /**
  84030. * Returns true if the layer contains information to display, otherwise false.
  84031. */
  84032. HighlightLayer.prototype.shouldRender = function () {
  84033. if (_super.prototype.shouldRender.call(this)) {
  84034. return this._meshes ? true : false;
  84035. }
  84036. return false;
  84037. };
  84038. /**
  84039. * Returns true if the mesh should render, otherwise false.
  84040. * @param mesh The mesh to render
  84041. * @returns true if it should render otherwise false
  84042. */
  84043. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84044. // Excluded Mesh
  84045. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84046. return false;
  84047. }
  84048. ;
  84049. return true;
  84050. };
  84051. /**
  84052. * Sets the required values for both the emissive texture and and the main color.
  84053. */
  84054. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84055. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84056. if (highlightLayerMesh) {
  84057. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84058. }
  84059. else {
  84060. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84061. }
  84062. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84063. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84064. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84065. }
  84066. else {
  84067. this._emissiveTextureAndColor.texture = null;
  84068. }
  84069. };
  84070. /**
  84071. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84072. * @param mesh The mesh to exclude from the highlight layer
  84073. */
  84074. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84075. if (!this._excludedMeshes) {
  84076. return;
  84077. }
  84078. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84079. if (!meshExcluded) {
  84080. this._excludedMeshes[mesh.uniqueId] = {
  84081. mesh: mesh,
  84082. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84083. mesh.getEngine().setStencilBuffer(false);
  84084. }),
  84085. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84086. mesh.getEngine().setStencilBuffer(true);
  84087. }),
  84088. };
  84089. }
  84090. };
  84091. /**
  84092. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84093. * @param mesh The mesh to highlight
  84094. */
  84095. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84096. if (!this._excludedMeshes) {
  84097. return;
  84098. }
  84099. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84100. if (meshExcluded) {
  84101. if (meshExcluded.beforeRender) {
  84102. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84103. }
  84104. if (meshExcluded.afterRender) {
  84105. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84106. }
  84107. }
  84108. this._excludedMeshes[mesh.uniqueId] = null;
  84109. };
  84110. /**
  84111. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84112. * @param mesh mesh to test
  84113. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84114. */
  84115. HighlightLayer.prototype.hasMesh = function (mesh) {
  84116. if (!this._meshes) {
  84117. return false;
  84118. }
  84119. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84120. };
  84121. /**
  84122. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84123. * @param mesh The mesh to highlight
  84124. * @param color The color of the highlight
  84125. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84126. */
  84127. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84128. var _this = this;
  84129. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84130. if (!this._meshes) {
  84131. return;
  84132. }
  84133. var meshHighlight = this._meshes[mesh.uniqueId];
  84134. if (meshHighlight) {
  84135. meshHighlight.color = color;
  84136. }
  84137. else {
  84138. this._meshes[mesh.uniqueId] = {
  84139. mesh: mesh,
  84140. color: color,
  84141. // Lambda required for capture due to Observable this context
  84142. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84143. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84144. _this._defaultStencilReference(mesh);
  84145. }
  84146. else {
  84147. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84148. }
  84149. }),
  84150. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84151. glowEmissiveOnly: glowEmissiveOnly
  84152. };
  84153. }
  84154. this._shouldRender = true;
  84155. };
  84156. /**
  84157. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84158. * @param mesh The mesh to highlight
  84159. */
  84160. HighlightLayer.prototype.removeMesh = function (mesh) {
  84161. if (!this._meshes) {
  84162. return;
  84163. }
  84164. var meshHighlight = this._meshes[mesh.uniqueId];
  84165. if (meshHighlight) {
  84166. if (meshHighlight.observerHighlight) {
  84167. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84168. }
  84169. if (meshHighlight.observerDefault) {
  84170. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84171. }
  84172. delete this._meshes[mesh.uniqueId];
  84173. }
  84174. this._shouldRender = false;
  84175. for (var meshHighlightToCheck in this._meshes) {
  84176. if (this._meshes[meshHighlightToCheck]) {
  84177. this._shouldRender = true;
  84178. break;
  84179. }
  84180. }
  84181. };
  84182. /**
  84183. * Force the stencil to the normal expected value for none glowing parts
  84184. */
  84185. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84186. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84187. };
  84188. /**
  84189. * Free any resources and references associated to a mesh.
  84190. * Internal use
  84191. * @param mesh The mesh to free.
  84192. */
  84193. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84194. this.removeMesh(mesh);
  84195. this.removeExcludedMesh(mesh);
  84196. };
  84197. /**
  84198. * Dispose the highlight layer and free resources.
  84199. */
  84200. HighlightLayer.prototype.dispose = function () {
  84201. if (this._meshes) {
  84202. // Clean mesh references
  84203. for (var id in this._meshes) {
  84204. var meshHighlight = this._meshes[id];
  84205. if (meshHighlight && meshHighlight.mesh) {
  84206. if (meshHighlight.observerHighlight) {
  84207. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84208. }
  84209. if (meshHighlight.observerDefault) {
  84210. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84211. }
  84212. }
  84213. }
  84214. this._meshes = null;
  84215. }
  84216. if (this._excludedMeshes) {
  84217. for (var id in this._excludedMeshes) {
  84218. var meshHighlight = this._excludedMeshes[id];
  84219. if (meshHighlight) {
  84220. if (meshHighlight.beforeRender) {
  84221. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84222. }
  84223. if (meshHighlight.afterRender) {
  84224. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84225. }
  84226. }
  84227. }
  84228. this._excludedMeshes = null;
  84229. }
  84230. _super.prototype.dispose.call(this);
  84231. };
  84232. /**
  84233. * Effect Name of the highlight layer.
  84234. */
  84235. HighlightLayer.EffectName = "HighlightLayer";
  84236. /**
  84237. * The neutral color used during the preparation of the glow effect.
  84238. * This is black by default as the blend operation is a blend operation.
  84239. */
  84240. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84241. /**
  84242. * Stencil value used for glowing meshes.
  84243. */
  84244. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84245. /**
  84246. * Stencil value used for the other meshes in the scene.
  84247. */
  84248. HighlightLayer.NormalMeshStencilReference = 0x01;
  84249. return HighlightLayer;
  84250. }(BABYLON.EffectLayer));
  84251. BABYLON.HighlightLayer = HighlightLayer;
  84252. })(BABYLON || (BABYLON = {}));
  84253. //# sourceMappingURL=babylon.highlightLayer.js.map
  84254. var BABYLON;
  84255. (function (BABYLON) {
  84256. /**
  84257. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84258. *
  84259. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84260. * glowy meshes to your scene.
  84261. *
  84262. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84263. */
  84264. var GlowLayer = /** @class */ (function (_super) {
  84265. __extends(GlowLayer, _super);
  84266. /**
  84267. * Instantiates a new glow Layer and references it to the scene.
  84268. * @param name The name of the layer
  84269. * @param scene The scene to use the layer in
  84270. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84271. */
  84272. function GlowLayer(name, scene, options) {
  84273. var _this = _super.call(this, name, scene) || this;
  84274. _this.name = name;
  84275. _this._intensity = 1.0;
  84276. _this._includedOnlyMeshes = [];
  84277. _this._excludedMeshes = [];
  84278. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84279. // Adapt options
  84280. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84281. // Initialize the layer
  84282. _this._init({
  84283. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84284. camera: _this._options.camera,
  84285. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84286. mainTextureRatio: _this._options.mainTextureRatio
  84287. });
  84288. return _this;
  84289. }
  84290. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84291. /**
  84292. * Gets the kernel size of the blur.
  84293. */
  84294. get: function () {
  84295. return this._horizontalBlurPostprocess1.kernel;
  84296. },
  84297. /**
  84298. * Sets the kernel size of the blur.
  84299. */
  84300. set: function (value) {
  84301. this._horizontalBlurPostprocess1.kernel = value;
  84302. this._verticalBlurPostprocess1.kernel = value;
  84303. this._horizontalBlurPostprocess2.kernel = value;
  84304. this._verticalBlurPostprocess2.kernel = value;
  84305. },
  84306. enumerable: true,
  84307. configurable: true
  84308. });
  84309. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84310. /**
  84311. * Gets the glow intensity.
  84312. */
  84313. get: function () {
  84314. return this._intensity;
  84315. },
  84316. /**
  84317. * Sets the glow intensity.
  84318. */
  84319. set: function (value) {
  84320. this._intensity = value;
  84321. },
  84322. enumerable: true,
  84323. configurable: true
  84324. });
  84325. /**
  84326. * Get the effect name of the layer.
  84327. * @return The effect name
  84328. */
  84329. GlowLayer.prototype.getEffectName = function () {
  84330. return GlowLayer.EffectName;
  84331. };
  84332. /**
  84333. * Create the merge effect. This is the shader use to blit the information back
  84334. * to the main canvas at the end of the scene rendering.
  84335. */
  84336. GlowLayer.prototype._createMergeEffect = function () {
  84337. // Effect
  84338. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84339. };
  84340. /**
  84341. * Creates the render target textures and post processes used in the glow layer.
  84342. */
  84343. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84344. var _this = this;
  84345. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84346. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84347. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84348. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84349. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84350. width: blurTextureWidth,
  84351. height: blurTextureHeight
  84352. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84353. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84354. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84355. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84356. this._blurTexture1.renderParticles = false;
  84357. this._blurTexture1.ignoreCameraViewport = true;
  84358. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84359. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84360. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84361. width: blurTextureWidth2,
  84362. height: blurTextureHeight2
  84363. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84364. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84365. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84366. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84367. this._blurTexture2.renderParticles = false;
  84368. this._blurTexture2.ignoreCameraViewport = true;
  84369. this._textures = [this._blurTexture1, this._blurTexture2];
  84370. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84371. width: blurTextureWidth,
  84372. height: blurTextureHeight
  84373. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84374. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84375. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84376. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84377. effect.setTexture("textureSampler", _this._mainTexture);
  84378. });
  84379. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84380. width: blurTextureWidth,
  84381. height: blurTextureHeight
  84382. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84383. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84384. width: blurTextureWidth2,
  84385. height: blurTextureHeight2
  84386. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84387. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84388. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84389. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84390. effect.setTexture("textureSampler", _this._blurTexture1);
  84391. });
  84392. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84393. width: blurTextureWidth2,
  84394. height: blurTextureHeight2
  84395. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84396. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84397. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84398. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84399. this._mainTexture.samples = this._options.mainTextureSamples;
  84400. this._mainTexture.onAfterUnbindObservable.add(function () {
  84401. var internalTexture = _this._blurTexture1.getInternalTexture();
  84402. if (internalTexture) {
  84403. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84404. internalTexture = _this._blurTexture2.getInternalTexture();
  84405. if (internalTexture) {
  84406. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84407. }
  84408. }
  84409. });
  84410. // Prevent autoClear.
  84411. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84412. };
  84413. /**
  84414. * Checks for the readiness of the element composing the layer.
  84415. * @param subMesh the mesh to check for
  84416. * @param useInstances specify wether or not to use instances to render the mesh
  84417. * @param emissiveTexture the associated emissive texture used to generate the glow
  84418. * @return true if ready otherwise, false
  84419. */
  84420. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84421. var material = subMesh.getMaterial();
  84422. var mesh = subMesh.getRenderingMesh();
  84423. if (!material || !mesh) {
  84424. return false;
  84425. }
  84426. var emissiveTexture = material.emissiveTexture;
  84427. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84428. };
  84429. /**
  84430. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84431. */
  84432. GlowLayer.prototype.needStencil = function () {
  84433. return false;
  84434. };
  84435. /**
  84436. * Implementation specific of rendering the generating effect on the main canvas.
  84437. * @param effect The effect used to render through
  84438. */
  84439. GlowLayer.prototype._internalRender = function (effect) {
  84440. // Texture
  84441. effect.setTexture("textureSampler", this._blurTexture1);
  84442. effect.setTexture("textureSampler2", this._blurTexture2);
  84443. effect.setFloat("offset", this._intensity);
  84444. // Cache
  84445. var engine = this._engine;
  84446. var previousStencilBuffer = engine.getStencilBuffer();
  84447. // Draw order
  84448. engine.setStencilBuffer(false);
  84449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84450. // Draw order
  84451. engine.setStencilBuffer(previousStencilBuffer);
  84452. };
  84453. /**
  84454. * Sets the required values for both the emissive texture and and the main color.
  84455. */
  84456. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84457. var textureLevel = 1.0;
  84458. if (this.customEmissiveTextureSelector) {
  84459. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84460. }
  84461. else {
  84462. if (material) {
  84463. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84464. if (this._emissiveTextureAndColor.texture) {
  84465. textureLevel = this._emissiveTextureAndColor.texture.level;
  84466. }
  84467. }
  84468. else {
  84469. this._emissiveTextureAndColor.texture = null;
  84470. }
  84471. }
  84472. if (this.customEmissiveColorSelector) {
  84473. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84474. }
  84475. else {
  84476. if (material.emissiveColor) {
  84477. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84478. }
  84479. else {
  84480. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84481. }
  84482. }
  84483. };
  84484. /**
  84485. * Returns true if the mesh should render, otherwise false.
  84486. * @param mesh The mesh to render
  84487. * @returns true if it should render otherwise false
  84488. */
  84489. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84490. return this.hasMesh(mesh);
  84491. };
  84492. /**
  84493. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84494. * @param mesh The mesh to exclude from the glow layer
  84495. */
  84496. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84497. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84498. this._excludedMeshes.push(mesh.uniqueId);
  84499. }
  84500. };
  84501. /**
  84502. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84503. * @param mesh The mesh to remove
  84504. */
  84505. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84506. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84507. if (index !== -1) {
  84508. this._excludedMeshes.splice(index, 1);
  84509. }
  84510. };
  84511. /**
  84512. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84513. * @param mesh The mesh to include in the glow layer
  84514. */
  84515. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84516. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84517. this._includedOnlyMeshes.push(mesh.uniqueId);
  84518. }
  84519. };
  84520. /**
  84521. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84522. * @param mesh The mesh to remove
  84523. */
  84524. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84525. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84526. if (index !== -1) {
  84527. this._includedOnlyMeshes.splice(index, 1);
  84528. }
  84529. };
  84530. /**
  84531. * Determine if a given mesh will be used in the glow layer
  84532. * @param mesh The mesh to test
  84533. * @returns true if the mesh will be highlighted by the current glow layer
  84534. */
  84535. GlowLayer.prototype.hasMesh = function (mesh) {
  84536. // Included Mesh
  84537. if (this._includedOnlyMeshes.length) {
  84538. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84539. }
  84540. ;
  84541. // Excluded Mesh
  84542. if (this._excludedMeshes.length) {
  84543. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84544. }
  84545. ;
  84546. return true;
  84547. };
  84548. /**
  84549. * Free any resources and references associated to a mesh.
  84550. * Internal use
  84551. * @param mesh The mesh to free.
  84552. */
  84553. GlowLayer.prototype._disposeMesh = function (mesh) {
  84554. this.removeIncludedOnlyMesh(mesh);
  84555. this.removeExcludedMesh(mesh);
  84556. };
  84557. /**
  84558. * Effect Name of the layer.
  84559. */
  84560. GlowLayer.EffectName = "GlowLayer";
  84561. /**
  84562. * The default blur kernel size used for the glow.
  84563. */
  84564. GlowLayer.DefaultBlurKernelSize = 32;
  84565. /**
  84566. * The default texture size ratio used for the glow.
  84567. */
  84568. GlowLayer.DefaultTextureRatio = 0.5;
  84569. return GlowLayer;
  84570. }(BABYLON.EffectLayer));
  84571. BABYLON.GlowLayer = GlowLayer;
  84572. })(BABYLON || (BABYLON = {}));
  84573. //# sourceMappingURL=babylon.glowLayer.js.map
  84574. var BABYLON;
  84575. (function (BABYLON) {
  84576. /**
  84577. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84578. */
  84579. var AssetTaskState;
  84580. (function (AssetTaskState) {
  84581. /**
  84582. * Initialization
  84583. */
  84584. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84585. /**
  84586. * Running
  84587. */
  84588. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84589. /**
  84590. * Done
  84591. */
  84592. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84593. /**
  84594. * Error
  84595. */
  84596. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84597. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84598. /**
  84599. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84600. */
  84601. var AbstractAssetTask = /** @class */ (function () {
  84602. /**
  84603. * Creates a new {BABYLON.AssetsManager}
  84604. * @param name defines the name of the task
  84605. */
  84606. function AbstractAssetTask(
  84607. /**
  84608. * Task name
  84609. */ name) {
  84610. this.name = name;
  84611. this._isCompleted = false;
  84612. this._taskState = AssetTaskState.INIT;
  84613. }
  84614. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84615. /**
  84616. * Get if the task is completed
  84617. */
  84618. get: function () {
  84619. return this._isCompleted;
  84620. },
  84621. enumerable: true,
  84622. configurable: true
  84623. });
  84624. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84625. /**
  84626. * Gets the current state of the task
  84627. */
  84628. get: function () {
  84629. return this._taskState;
  84630. },
  84631. enumerable: true,
  84632. configurable: true
  84633. });
  84634. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84635. /**
  84636. * Gets the current error object (if task is in error)
  84637. */
  84638. get: function () {
  84639. return this._errorObject;
  84640. },
  84641. enumerable: true,
  84642. configurable: true
  84643. });
  84644. /**
  84645. * Internal only
  84646. * @ignore
  84647. */
  84648. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84649. if (this._errorObject) {
  84650. return;
  84651. }
  84652. this._errorObject = {
  84653. message: message,
  84654. exception: exception
  84655. };
  84656. };
  84657. /**
  84658. * Execute the current task
  84659. * @param scene defines the scene where you want your assets to be loaded
  84660. * @param onSuccess is a callback called when the task is successfully executed
  84661. * @param onError is a callback called if an error occurs
  84662. */
  84663. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84664. var _this = this;
  84665. this._taskState = AssetTaskState.RUNNING;
  84666. this.runTask(scene, function () {
  84667. _this.onDoneCallback(onSuccess, onError);
  84668. }, function (msg, exception) {
  84669. _this.onErrorCallback(onError, msg, exception);
  84670. });
  84671. };
  84672. /**
  84673. * Execute the current task
  84674. * @param scene defines the scene where you want your assets to be loaded
  84675. * @param onSuccess is a callback called when the task is successfully executed
  84676. * @param onError is a callback called if an error occurs
  84677. */
  84678. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84679. throw new Error("runTask is not implemented");
  84680. };
  84681. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84682. this._taskState = AssetTaskState.ERROR;
  84683. this._errorObject = {
  84684. message: message,
  84685. exception: exception
  84686. };
  84687. if (this.onError) {
  84688. this.onError(this, message, exception);
  84689. }
  84690. onError();
  84691. };
  84692. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  84693. try {
  84694. this._taskState = AssetTaskState.DONE;
  84695. this._isCompleted = true;
  84696. if (this.onSuccess) {
  84697. this.onSuccess(this);
  84698. }
  84699. onSuccess();
  84700. }
  84701. catch (e) {
  84702. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  84703. }
  84704. };
  84705. return AbstractAssetTask;
  84706. }());
  84707. BABYLON.AbstractAssetTask = AbstractAssetTask;
  84708. /**
  84709. * Class used to share progress information about assets loading
  84710. */
  84711. var AssetsProgressEvent = /** @class */ (function () {
  84712. /**
  84713. * Creates a {BABYLON.AssetsProgressEvent}
  84714. * @param remainingCount defines the number of remaining tasks to process
  84715. * @param totalCount defines the total number of tasks
  84716. * @param task defines the task that was just processed
  84717. */
  84718. function AssetsProgressEvent(remainingCount, totalCount, task) {
  84719. this.remainingCount = remainingCount;
  84720. this.totalCount = totalCount;
  84721. this.task = task;
  84722. }
  84723. return AssetsProgressEvent;
  84724. }());
  84725. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  84726. /**
  84727. * Define a task used by {BABYLON.AssetsManager} to load meshes
  84728. */
  84729. var MeshAssetTask = /** @class */ (function (_super) {
  84730. __extends(MeshAssetTask, _super);
  84731. /**
  84732. * Creates a new {BABYLON.MeshAssetTask}
  84733. * @param name defines the name of the task
  84734. * @param meshesNames defines the list of mesh's names you want to load
  84735. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  84736. * @param sceneFilename defines the filename of the scene to load from
  84737. */
  84738. function MeshAssetTask(
  84739. /**
  84740. * Defines the name of the task
  84741. */
  84742. name,
  84743. /**
  84744. * Defines the list of mesh's names you want to load
  84745. */
  84746. meshesNames,
  84747. /**
  84748. * Defines the root url to use as a base to load your meshes and associated resources
  84749. */
  84750. rootUrl,
  84751. /**
  84752. * Defines the filename of the scene to load from
  84753. */
  84754. sceneFilename) {
  84755. var _this = _super.call(this, name) || this;
  84756. _this.name = name;
  84757. _this.meshesNames = meshesNames;
  84758. _this.rootUrl = rootUrl;
  84759. _this.sceneFilename = sceneFilename;
  84760. return _this;
  84761. }
  84762. /**
  84763. * Execute the current task
  84764. * @param scene defines the scene where you want your assets to be loaded
  84765. * @param onSuccess is a callback called when the task is successfully executed
  84766. * @param onError is a callback called if an error occurs
  84767. */
  84768. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84769. var _this = this;
  84770. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  84771. _this.loadedMeshes = meshes;
  84772. _this.loadedParticleSystems = particleSystems;
  84773. _this.loadedSkeletons = skeletons;
  84774. onSuccess();
  84775. }, null, function (scene, message, exception) {
  84776. onError(message, exception);
  84777. });
  84778. };
  84779. return MeshAssetTask;
  84780. }(AbstractAssetTask));
  84781. BABYLON.MeshAssetTask = MeshAssetTask;
  84782. /**
  84783. * Define a task used by {BABYLON.AssetsManager} to load text content
  84784. */
  84785. var TextFileAssetTask = /** @class */ (function (_super) {
  84786. __extends(TextFileAssetTask, _super);
  84787. /**
  84788. * Creates a new TextFileAssetTask object
  84789. * @param name defines the name of the task
  84790. * @param url defines the location of the file to load
  84791. */
  84792. function TextFileAssetTask(
  84793. /**
  84794. * Defines the name of the task
  84795. */
  84796. name,
  84797. /**
  84798. * Defines the location of the file to load
  84799. */
  84800. url) {
  84801. var _this = _super.call(this, name) || this;
  84802. _this.name = name;
  84803. _this.url = url;
  84804. return _this;
  84805. }
  84806. /**
  84807. * Execute the current task
  84808. * @param scene defines the scene where you want your assets to be loaded
  84809. * @param onSuccess is a callback called when the task is successfully executed
  84810. * @param onError is a callback called if an error occurs
  84811. */
  84812. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84813. var _this = this;
  84814. scene._loadFile(this.url, function (data) {
  84815. _this.text = data;
  84816. onSuccess();
  84817. }, undefined, false, false, function (request, exception) {
  84818. if (request) {
  84819. onError(request.status + " " + request.statusText, exception);
  84820. }
  84821. });
  84822. };
  84823. return TextFileAssetTask;
  84824. }(AbstractAssetTask));
  84825. BABYLON.TextFileAssetTask = TextFileAssetTask;
  84826. /**
  84827. * Define a task used by {BABYLON.AssetsManager} to load binary data
  84828. */
  84829. var BinaryFileAssetTask = /** @class */ (function (_super) {
  84830. __extends(BinaryFileAssetTask, _super);
  84831. /**
  84832. * Creates a new BinaryFileAssetTask object
  84833. * @param name defines the name of the new task
  84834. * @param url defines the location of the file to load
  84835. */
  84836. function BinaryFileAssetTask(
  84837. /**
  84838. * Defines the name of the task
  84839. */
  84840. name,
  84841. /**
  84842. * Defines the location of the file to load
  84843. */
  84844. url) {
  84845. var _this = _super.call(this, name) || this;
  84846. _this.name = name;
  84847. _this.url = url;
  84848. return _this;
  84849. }
  84850. /**
  84851. * Execute the current task
  84852. * @param scene defines the scene where you want your assets to be loaded
  84853. * @param onSuccess is a callback called when the task is successfully executed
  84854. * @param onError is a callback called if an error occurs
  84855. */
  84856. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84857. var _this = this;
  84858. scene._loadFile(this.url, function (data) {
  84859. _this.data = data;
  84860. onSuccess();
  84861. }, undefined, true, true, function (request, exception) {
  84862. if (request) {
  84863. onError(request.status + " " + request.statusText, exception);
  84864. }
  84865. });
  84866. };
  84867. return BinaryFileAssetTask;
  84868. }(AbstractAssetTask));
  84869. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  84870. /**
  84871. * Define a task used by {BABYLON.AssetsManager} to load images
  84872. */
  84873. var ImageAssetTask = /** @class */ (function (_super) {
  84874. __extends(ImageAssetTask, _super);
  84875. /**
  84876. * Creates a new ImageAssetTask
  84877. * @param name defines the name of the task
  84878. * @param url defines the location of the image to load
  84879. */
  84880. function ImageAssetTask(
  84881. /**
  84882. * Defines the name of the task
  84883. */
  84884. name,
  84885. /**
  84886. * Defines the location of the image to load
  84887. */
  84888. url) {
  84889. var _this = _super.call(this, name) || this;
  84890. _this.name = name;
  84891. _this.url = url;
  84892. return _this;
  84893. }
  84894. /**
  84895. * Execute the current task
  84896. * @param scene defines the scene where you want your assets to be loaded
  84897. * @param onSuccess is a callback called when the task is successfully executed
  84898. * @param onError is a callback called if an error occurs
  84899. */
  84900. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84901. var _this = this;
  84902. var img = new Image();
  84903. BABYLON.Tools.SetCorsBehavior(this.url, img);
  84904. img.onload = function () {
  84905. _this.image = img;
  84906. onSuccess();
  84907. };
  84908. img.onerror = function (err) {
  84909. onError("Error loading image", err);
  84910. };
  84911. img.src = this.url;
  84912. };
  84913. return ImageAssetTask;
  84914. }(AbstractAssetTask));
  84915. BABYLON.ImageAssetTask = ImageAssetTask;
  84916. /**
  84917. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84918. */
  84919. var TextureAssetTask = /** @class */ (function (_super) {
  84920. __extends(TextureAssetTask, _super);
  84921. /**
  84922. * Creates a new TextureAssetTask object
  84923. * @param name defines the name of the task
  84924. * @param url defines the location of the file to load
  84925. * @param noMipmap defines if mipmap should not be generated (default is false)
  84926. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84927. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84928. */
  84929. function TextureAssetTask(
  84930. /**
  84931. * Defines the name of the task
  84932. */
  84933. name,
  84934. /**
  84935. * Defines the location of the file to load
  84936. */
  84937. url,
  84938. /**
  84939. * Defines if mipmap should not be generated (default is false)
  84940. */
  84941. noMipmap,
  84942. /**
  84943. * Defines if texture must be inverted on Y axis (default is false)
  84944. */
  84945. invertY,
  84946. /**
  84947. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84948. */
  84949. samplingMode) {
  84950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84951. var _this = _super.call(this, name) || this;
  84952. _this.name = name;
  84953. _this.url = url;
  84954. _this.noMipmap = noMipmap;
  84955. _this.invertY = invertY;
  84956. _this.samplingMode = samplingMode;
  84957. return _this;
  84958. }
  84959. /**
  84960. * Execute the current task
  84961. * @param scene defines the scene where you want your assets to be loaded
  84962. * @param onSuccess is a callback called when the task is successfully executed
  84963. * @param onError is a callback called if an error occurs
  84964. */
  84965. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84966. var onload = function () {
  84967. onSuccess();
  84968. };
  84969. var onerror = function (message, exception) {
  84970. onError(message, exception);
  84971. };
  84972. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84973. };
  84974. return TextureAssetTask;
  84975. }(AbstractAssetTask));
  84976. BABYLON.TextureAssetTask = TextureAssetTask;
  84977. /**
  84978. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84979. */
  84980. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84981. __extends(CubeTextureAssetTask, _super);
  84982. /**
  84983. * Creates a new CubeTextureAssetTask
  84984. * @param name defines the name of the task
  84985. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84986. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84987. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84988. * @param files defines the explicit list of files (undefined by default)
  84989. */
  84990. function CubeTextureAssetTask(
  84991. /**
  84992. * Defines the name of the task
  84993. */
  84994. name,
  84995. /**
  84996. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84997. */
  84998. url,
  84999. /**
  85000. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85001. */
  85002. extensions,
  85003. /**
  85004. * Defines if mipmaps should not be generated (default is false)
  85005. */
  85006. noMipmap,
  85007. /**
  85008. * Defines the explicit list of files (undefined by default)
  85009. */
  85010. files) {
  85011. var _this = _super.call(this, name) || this;
  85012. _this.name = name;
  85013. _this.url = url;
  85014. _this.extensions = extensions;
  85015. _this.noMipmap = noMipmap;
  85016. _this.files = files;
  85017. return _this;
  85018. }
  85019. /**
  85020. * Execute the current task
  85021. * @param scene defines the scene where you want your assets to be loaded
  85022. * @param onSuccess is a callback called when the task is successfully executed
  85023. * @param onError is a callback called if an error occurs
  85024. */
  85025. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85026. var onload = function () {
  85027. onSuccess();
  85028. };
  85029. var onerror = function (message, exception) {
  85030. onError(message, exception);
  85031. };
  85032. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85033. };
  85034. return CubeTextureAssetTask;
  85035. }(AbstractAssetTask));
  85036. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85037. /**
  85038. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85039. */
  85040. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85041. __extends(HDRCubeTextureAssetTask, _super);
  85042. /**
  85043. * Creates a new HDRCubeTextureAssetTask object
  85044. * @param name defines the name of the task
  85045. * @param url defines the location of the file to load
  85046. * @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.
  85047. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85048. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85049. * @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)
  85050. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85051. */
  85052. function HDRCubeTextureAssetTask(
  85053. /**
  85054. * Defines the name of the task
  85055. */
  85056. name,
  85057. /**
  85058. * Defines the location of the file to load
  85059. */
  85060. url,
  85061. /**
  85062. * 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.
  85063. */
  85064. size,
  85065. /**
  85066. * Defines if mipmaps should not be generated (default is false)
  85067. */
  85068. noMipmap,
  85069. /**
  85070. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85071. */
  85072. generateHarmonics,
  85073. /**
  85074. * 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)
  85075. */
  85076. useInGammaSpace,
  85077. /**
  85078. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85079. */
  85080. usePMREMGenerator) {
  85081. if (noMipmap === void 0) { noMipmap = false; }
  85082. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85083. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85084. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85085. var _this = _super.call(this, name) || this;
  85086. _this.name = name;
  85087. _this.url = url;
  85088. _this.size = size;
  85089. _this.noMipmap = noMipmap;
  85090. _this.generateHarmonics = generateHarmonics;
  85091. _this.useInGammaSpace = useInGammaSpace;
  85092. _this.usePMREMGenerator = usePMREMGenerator;
  85093. return _this;
  85094. }
  85095. /**
  85096. * Execute the current task
  85097. * @param scene defines the scene where you want your assets to be loaded
  85098. * @param onSuccess is a callback called when the task is successfully executed
  85099. * @param onError is a callback called if an error occurs
  85100. */
  85101. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85102. var onload = function () {
  85103. onSuccess();
  85104. };
  85105. var onerror = function (message, exception) {
  85106. onError(message, exception);
  85107. };
  85108. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85109. };
  85110. return HDRCubeTextureAssetTask;
  85111. }(AbstractAssetTask));
  85112. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85113. /**
  85114. * This class can be used to easily import assets into a scene
  85115. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85116. */
  85117. var AssetsManager = /** @class */ (function () {
  85118. /**
  85119. * Creates a new AssetsManager
  85120. * @param scene defines the scene to work on
  85121. */
  85122. function AssetsManager(scene) {
  85123. this._isLoading = false;
  85124. this._tasks = new Array();
  85125. this._waitingTasksCount = 0;
  85126. this._totalTasksCount = 0;
  85127. /**
  85128. * Observable called when all tasks are processed
  85129. */
  85130. this.onTaskSuccessObservable = new BABYLON.Observable();
  85131. /**
  85132. * Observable called when a task had an error
  85133. */
  85134. this.onTaskErrorObservable = new BABYLON.Observable();
  85135. /**
  85136. * Observable called when a task is successful
  85137. */
  85138. this.onTasksDoneObservable = new BABYLON.Observable();
  85139. /**
  85140. * Observable called when a task is done (whatever the result is)
  85141. */
  85142. this.onProgressObservable = new BABYLON.Observable();
  85143. /**
  85144. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85145. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85146. */
  85147. this.useDefaultLoadingScreen = true;
  85148. this._scene = scene;
  85149. }
  85150. /**
  85151. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85152. * @param taskName defines the name of the new task
  85153. * @param meshesNames defines the name of meshes to load
  85154. * @param rootUrl defines the root url to use to locate files
  85155. * @param sceneFilename defines the filename of the scene file
  85156. * @returns a new {BABYLON.MeshAssetTask} object
  85157. */
  85158. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85159. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85160. this._tasks.push(task);
  85161. return task;
  85162. };
  85163. /**
  85164. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85165. * @param taskName defines the name of the new task
  85166. * @param url defines the url of the file to load
  85167. * @returns a new {BABYLON.TextFileAssetTask} object
  85168. */
  85169. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85170. var task = new TextFileAssetTask(taskName, url);
  85171. this._tasks.push(task);
  85172. return task;
  85173. };
  85174. /**
  85175. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85176. * @param taskName defines the name of the new task
  85177. * @param url defines the url of the file to load
  85178. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85179. */
  85180. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85181. var task = new BinaryFileAssetTask(taskName, url);
  85182. this._tasks.push(task);
  85183. return task;
  85184. };
  85185. /**
  85186. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85187. * @param taskName defines the name of the new task
  85188. * @param url defines the url of the file to load
  85189. * @returns a new {BABYLON.ImageAssetTask} object
  85190. */
  85191. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85192. var task = new ImageAssetTask(taskName, url);
  85193. this._tasks.push(task);
  85194. return task;
  85195. };
  85196. /**
  85197. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85198. * @param taskName defines the name of the new task
  85199. * @param url defines the url of the file to load
  85200. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85201. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85202. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85203. * @returns a new {BABYLON.TextureAssetTask} object
  85204. */
  85205. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85207. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85208. this._tasks.push(task);
  85209. return task;
  85210. };
  85211. /**
  85212. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85213. * @param taskName defines the name of the new task
  85214. * @param url defines the url of the file to load
  85215. * @param extensions defines the extension to use to load the cube map (can be null)
  85216. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85217. * @param files defines the list of files to load (can be null)
  85218. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85219. */
  85220. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85221. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85222. this._tasks.push(task);
  85223. return task;
  85224. };
  85225. /**
  85226. *
  85227. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85228. * @param taskName defines the name of the new task
  85229. * @param url defines the url of the file to load
  85230. * @param size defines the size you want for the cubemap (can be null)
  85231. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85232. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85233. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85234. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85235. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85236. */
  85237. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85238. if (noMipmap === void 0) { noMipmap = false; }
  85239. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85240. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85241. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85242. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85243. this._tasks.push(task);
  85244. return task;
  85245. };
  85246. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85247. var _this = this;
  85248. this._waitingTasksCount--;
  85249. try {
  85250. if (task.taskState === AssetTaskState.DONE) {
  85251. // Let's remove successfull tasks
  85252. BABYLON.Tools.SetImmediate(function () {
  85253. var index = _this._tasks.indexOf(task);
  85254. if (index > -1) {
  85255. _this._tasks.splice(index, 1);
  85256. }
  85257. });
  85258. }
  85259. if (this.onProgress) {
  85260. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85261. }
  85262. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85263. }
  85264. catch (e) {
  85265. BABYLON.Tools.Error("Error running progress callbacks.");
  85266. console.log(e);
  85267. }
  85268. if (this._waitingTasksCount === 0) {
  85269. try {
  85270. if (this.onFinish) {
  85271. this.onFinish(this._tasks);
  85272. }
  85273. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85274. }
  85275. catch (e) {
  85276. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85277. console.log(e);
  85278. }
  85279. this._isLoading = false;
  85280. this._scene.getEngine().hideLoadingUI();
  85281. }
  85282. };
  85283. AssetsManager.prototype._runTask = function (task) {
  85284. var _this = this;
  85285. var done = function () {
  85286. try {
  85287. if (_this.onTaskSuccess) {
  85288. _this.onTaskSuccess(task);
  85289. }
  85290. _this.onTaskSuccessObservable.notifyObservers(task);
  85291. _this._decreaseWaitingTasksCount(task);
  85292. }
  85293. catch (e) {
  85294. error("Error executing task success callbacks", e);
  85295. }
  85296. };
  85297. var error = function (message, exception) {
  85298. task._setErrorObject(message, exception);
  85299. if (_this.onTaskError) {
  85300. _this.onTaskError(task);
  85301. }
  85302. _this.onTaskErrorObservable.notifyObservers(task);
  85303. _this._decreaseWaitingTasksCount(task);
  85304. };
  85305. task.run(this._scene, done, error);
  85306. };
  85307. /**
  85308. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85309. * @return the current instance of the {BABYLON.AssetsManager}
  85310. */
  85311. AssetsManager.prototype.reset = function () {
  85312. this._isLoading = false;
  85313. this._tasks = new Array();
  85314. return this;
  85315. };
  85316. /**
  85317. * Start the loading process
  85318. * @return the current instance of the {BABYLON.AssetsManager}
  85319. */
  85320. AssetsManager.prototype.load = function () {
  85321. if (this._isLoading) {
  85322. return this;
  85323. }
  85324. this._isLoading = true;
  85325. this._waitingTasksCount = this._tasks.length;
  85326. this._totalTasksCount = this._tasks.length;
  85327. if (this._waitingTasksCount === 0) {
  85328. this._isLoading = false;
  85329. if (this.onFinish) {
  85330. this.onFinish(this._tasks);
  85331. }
  85332. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85333. return this;
  85334. }
  85335. if (this.useDefaultLoadingScreen) {
  85336. this._scene.getEngine().displayLoadingUI();
  85337. }
  85338. for (var index = 0; index < this._tasks.length; index++) {
  85339. var task = this._tasks[index];
  85340. this._runTask(task);
  85341. }
  85342. return this;
  85343. };
  85344. return AssetsManager;
  85345. }());
  85346. BABYLON.AssetsManager = AssetsManager;
  85347. })(BABYLON || (BABYLON = {}));
  85348. //# sourceMappingURL=babylon.assetsManager.js.map
  85349. var BABYLON;
  85350. (function (BABYLON) {
  85351. var serializedGeometries = [];
  85352. var serializeGeometry = function (geometry, serializationGeometries) {
  85353. if (serializedGeometries[geometry.id]) {
  85354. return;
  85355. }
  85356. if (geometry.doNotSerialize) {
  85357. return;
  85358. }
  85359. if (geometry instanceof BABYLON.BoxGeometry) {
  85360. serializationGeometries.boxes.push(geometry.serialize());
  85361. }
  85362. else if (geometry instanceof BABYLON.SphereGeometry) {
  85363. serializationGeometries.spheres.push(geometry.serialize());
  85364. }
  85365. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85366. serializationGeometries.cylinders.push(geometry.serialize());
  85367. }
  85368. else if (geometry instanceof BABYLON.TorusGeometry) {
  85369. serializationGeometries.toruses.push(geometry.serialize());
  85370. }
  85371. else if (geometry instanceof BABYLON.GroundGeometry) {
  85372. serializationGeometries.grounds.push(geometry.serialize());
  85373. }
  85374. else if (geometry instanceof BABYLON.Plane) {
  85375. serializationGeometries.planes.push(geometry.serialize());
  85376. }
  85377. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85378. serializationGeometries.torusKnots.push(geometry.serialize());
  85379. }
  85380. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85381. throw new Error("Unknown primitive type");
  85382. }
  85383. else {
  85384. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85385. }
  85386. serializedGeometries[geometry.id] = true;
  85387. };
  85388. var serializeMesh = function (mesh, serializationScene) {
  85389. var serializationObject = {};
  85390. // Geometry
  85391. var geometry = mesh._geometry;
  85392. if (geometry) {
  85393. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85394. // 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
  85395. serializeGeometry(geometry, serializationScene.geometries);
  85396. }
  85397. }
  85398. // Custom
  85399. if (mesh.serialize) {
  85400. mesh.serialize(serializationObject);
  85401. }
  85402. return serializationObject;
  85403. };
  85404. var finalizeSingleMesh = function (mesh, serializationObject) {
  85405. //only works if the mesh is already loaded
  85406. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85407. //serialize material
  85408. if (mesh.material) {
  85409. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85410. serializationObject.materials = serializationObject.materials || [];
  85411. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85412. serializationObject.materials.push(mesh.material.serialize());
  85413. }
  85414. }
  85415. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85416. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85417. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85418. serializationObject.multiMaterials.push(mesh.material.serialize());
  85419. }
  85420. }
  85421. }
  85422. //serialize geometry
  85423. var geometry = mesh._geometry;
  85424. if (geometry) {
  85425. if (!serializationObject.geometries) {
  85426. serializationObject.geometries = {};
  85427. serializationObject.geometries.boxes = [];
  85428. serializationObject.geometries.spheres = [];
  85429. serializationObject.geometries.cylinders = [];
  85430. serializationObject.geometries.toruses = [];
  85431. serializationObject.geometries.grounds = [];
  85432. serializationObject.geometries.planes = [];
  85433. serializationObject.geometries.torusKnots = [];
  85434. serializationObject.geometries.vertexData = [];
  85435. }
  85436. serializeGeometry(geometry, serializationObject.geometries);
  85437. }
  85438. // Skeletons
  85439. if (mesh.skeleton) {
  85440. serializationObject.skeletons = serializationObject.skeletons || [];
  85441. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85442. }
  85443. //serialize the actual mesh
  85444. serializationObject.meshes = serializationObject.meshes || [];
  85445. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85446. }
  85447. };
  85448. var SceneSerializer = /** @class */ (function () {
  85449. function SceneSerializer() {
  85450. }
  85451. SceneSerializer.ClearCache = function () {
  85452. serializedGeometries = [];
  85453. };
  85454. SceneSerializer.Serialize = function (scene) {
  85455. var serializationObject = {};
  85456. SceneSerializer.ClearCache();
  85457. // Scene
  85458. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85459. serializationObject.autoClear = scene.autoClear;
  85460. serializationObject.clearColor = scene.clearColor.asArray();
  85461. serializationObject.ambientColor = scene.ambientColor.asArray();
  85462. serializationObject.gravity = scene.gravity.asArray();
  85463. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85464. serializationObject.workerCollisions = scene.workerCollisions;
  85465. // Fog
  85466. if (scene.fogMode && scene.fogMode !== 0) {
  85467. serializationObject.fogMode = scene.fogMode;
  85468. serializationObject.fogColor = scene.fogColor.asArray();
  85469. serializationObject.fogStart = scene.fogStart;
  85470. serializationObject.fogEnd = scene.fogEnd;
  85471. serializationObject.fogDensity = scene.fogDensity;
  85472. }
  85473. //Physics
  85474. if (scene.isPhysicsEnabled()) {
  85475. var physicEngine = scene.getPhysicsEngine();
  85476. if (physicEngine) {
  85477. serializationObject.physicsEnabled = true;
  85478. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85479. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85480. }
  85481. }
  85482. // Metadata
  85483. if (scene.metadata) {
  85484. serializationObject.metadata = scene.metadata;
  85485. }
  85486. // Morph targets
  85487. serializationObject.morphTargetManagers = [];
  85488. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85489. var abstractMesh = _a[_i];
  85490. var manager = abstractMesh.morphTargetManager;
  85491. if (manager) {
  85492. serializationObject.morphTargetManagers.push(manager.serialize());
  85493. }
  85494. }
  85495. // Lights
  85496. serializationObject.lights = [];
  85497. var index;
  85498. var light;
  85499. for (index = 0; index < scene.lights.length; index++) {
  85500. light = scene.lights[index];
  85501. if (!light.doNotSerialize) {
  85502. serializationObject.lights.push(light.serialize());
  85503. }
  85504. }
  85505. // Cameras
  85506. serializationObject.cameras = [];
  85507. for (index = 0; index < scene.cameras.length; index++) {
  85508. var camera = scene.cameras[index];
  85509. if (!camera.doNotSerialize) {
  85510. serializationObject.cameras.push(camera.serialize());
  85511. }
  85512. }
  85513. if (scene.activeCamera) {
  85514. serializationObject.activeCameraID = scene.activeCamera.id;
  85515. }
  85516. // Animations
  85517. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85518. // Materials
  85519. serializationObject.materials = [];
  85520. serializationObject.multiMaterials = [];
  85521. var material;
  85522. for (index = 0; index < scene.materials.length; index++) {
  85523. material = scene.materials[index];
  85524. if (!material.doNotSerialize) {
  85525. serializationObject.materials.push(material.serialize());
  85526. }
  85527. }
  85528. // MultiMaterials
  85529. serializationObject.multiMaterials = [];
  85530. for (index = 0; index < scene.multiMaterials.length; index++) {
  85531. var multiMaterial = scene.multiMaterials[index];
  85532. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85533. }
  85534. // Environment texture
  85535. if (scene.environmentTexture) {
  85536. serializationObject.environmentTexture = scene.environmentTexture.name;
  85537. }
  85538. // Skeletons
  85539. serializationObject.skeletons = [];
  85540. for (index = 0; index < scene.skeletons.length; index++) {
  85541. var skeleton = scene.skeletons[index];
  85542. if (!skeleton.doNotSerialize) {
  85543. serializationObject.skeletons.push(skeleton.serialize());
  85544. }
  85545. }
  85546. // Transform nodes
  85547. serializationObject.transformNodes = [];
  85548. for (index = 0; index < scene.transformNodes.length; index++) {
  85549. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85550. }
  85551. // Geometries
  85552. serializationObject.geometries = {};
  85553. serializationObject.geometries.boxes = [];
  85554. serializationObject.geometries.spheres = [];
  85555. serializationObject.geometries.cylinders = [];
  85556. serializationObject.geometries.toruses = [];
  85557. serializationObject.geometries.grounds = [];
  85558. serializationObject.geometries.planes = [];
  85559. serializationObject.geometries.torusKnots = [];
  85560. serializationObject.geometries.vertexData = [];
  85561. serializedGeometries = [];
  85562. var geometries = scene.getGeometries();
  85563. for (index = 0; index < geometries.length; index++) {
  85564. var geometry = geometries[index];
  85565. if (geometry.isReady()) {
  85566. serializeGeometry(geometry, serializationObject.geometries);
  85567. }
  85568. }
  85569. // Meshes
  85570. serializationObject.meshes = [];
  85571. for (index = 0; index < scene.meshes.length; index++) {
  85572. var abstractMesh = scene.meshes[index];
  85573. if (abstractMesh instanceof BABYLON.Mesh) {
  85574. var mesh = abstractMesh;
  85575. if (!mesh.doNotSerialize) {
  85576. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85577. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85578. }
  85579. }
  85580. }
  85581. }
  85582. // Particles Systems
  85583. serializationObject.particleSystems = [];
  85584. for (index = 0; index < scene.particleSystems.length; index++) {
  85585. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85586. }
  85587. // Lens flares
  85588. serializationObject.lensFlareSystems = [];
  85589. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85590. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85591. }
  85592. // Shadows
  85593. serializationObject.shadowGenerators = [];
  85594. for (index = 0; index < scene.lights.length; index++) {
  85595. light = scene.lights[index];
  85596. var shadowGenerator = light.getShadowGenerator();
  85597. if (shadowGenerator) {
  85598. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85599. }
  85600. }
  85601. // Action Manager
  85602. if (scene.actionManager) {
  85603. serializationObject.actions = scene.actionManager.serialize("scene");
  85604. }
  85605. // Audio
  85606. serializationObject.sounds = [];
  85607. for (index = 0; index < scene.soundTracks.length; index++) {
  85608. var soundtrack = scene.soundTracks[index];
  85609. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85610. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85611. }
  85612. }
  85613. return serializationObject;
  85614. };
  85615. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85616. if (withParents === void 0) { withParents = false; }
  85617. if (withChildren === void 0) { withChildren = false; }
  85618. var serializationObject = {};
  85619. SceneSerializer.ClearCache();
  85620. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85621. if (withParents || withChildren) {
  85622. //deliberate for loop! not for each, appended should be processed as well.
  85623. for (var i = 0; i < toSerialize.length; ++i) {
  85624. if (withChildren) {
  85625. toSerialize[i].getDescendants().forEach(function (node) {
  85626. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85627. toSerialize.push(node);
  85628. }
  85629. });
  85630. }
  85631. //make sure the array doesn't contain the object already
  85632. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85633. toSerialize.push(toSerialize[i].parent);
  85634. }
  85635. }
  85636. }
  85637. toSerialize.forEach(function (mesh) {
  85638. finalizeSingleMesh(mesh, serializationObject);
  85639. });
  85640. return serializationObject;
  85641. };
  85642. return SceneSerializer;
  85643. }());
  85644. BABYLON.SceneSerializer = SceneSerializer;
  85645. })(BABYLON || (BABYLON = {}));
  85646. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85647. var BABYLON;
  85648. (function (BABYLON) {
  85649. var ReflectionProbe = /** @class */ (function () {
  85650. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85652. var _this = this;
  85653. this.name = name;
  85654. this._viewMatrix = BABYLON.Matrix.Identity();
  85655. this._target = BABYLON.Vector3.Zero();
  85656. this._add = BABYLON.Vector3.Zero();
  85657. this.invertYAxis = false;
  85658. this.position = BABYLON.Vector3.Zero();
  85659. this._scene = scene;
  85660. this._scene.reflectionProbes.push(this);
  85661. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85662. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85663. switch (faceIndex) {
  85664. case 0:
  85665. _this._add.copyFromFloats(1, 0, 0);
  85666. break;
  85667. case 1:
  85668. _this._add.copyFromFloats(-1, 0, 0);
  85669. break;
  85670. case 2:
  85671. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  85672. break;
  85673. case 3:
  85674. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  85675. break;
  85676. case 4:
  85677. _this._add.copyFromFloats(0, 0, 1);
  85678. break;
  85679. case 5:
  85680. _this._add.copyFromFloats(0, 0, -1);
  85681. break;
  85682. }
  85683. if (_this._attachedMesh) {
  85684. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85685. }
  85686. _this.position.addToRef(_this._add, _this._target);
  85687. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  85688. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  85689. scene._forcedViewPosition = _this.position;
  85690. });
  85691. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  85692. scene._forcedViewPosition = null;
  85693. scene.updateTransformMatrix(true);
  85694. });
  85695. if (scene.activeCamera) {
  85696. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85697. }
  85698. }
  85699. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  85700. get: function () {
  85701. return this._renderTargetTexture.samples;
  85702. },
  85703. set: function (value) {
  85704. this._renderTargetTexture.samples = value;
  85705. },
  85706. enumerable: true,
  85707. configurable: true
  85708. });
  85709. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  85710. get: function () {
  85711. return this._renderTargetTexture.refreshRate;
  85712. },
  85713. set: function (value) {
  85714. this._renderTargetTexture.refreshRate = value;
  85715. },
  85716. enumerable: true,
  85717. configurable: true
  85718. });
  85719. ReflectionProbe.prototype.getScene = function () {
  85720. return this._scene;
  85721. };
  85722. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  85723. get: function () {
  85724. return this._renderTargetTexture;
  85725. },
  85726. enumerable: true,
  85727. configurable: true
  85728. });
  85729. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  85730. get: function () {
  85731. return this._renderTargetTexture.renderList;
  85732. },
  85733. enumerable: true,
  85734. configurable: true
  85735. });
  85736. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  85737. this._attachedMesh = mesh;
  85738. };
  85739. /**
  85740. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  85741. *
  85742. * @param renderingGroupId The rendering group id corresponding to its index
  85743. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  85744. */
  85745. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  85746. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  85747. };
  85748. ReflectionProbe.prototype.dispose = function () {
  85749. var index = this._scene.reflectionProbes.indexOf(this);
  85750. if (index !== -1) {
  85751. // Remove from the scene if found
  85752. this._scene.reflectionProbes.splice(index, 1);
  85753. }
  85754. if (this._renderTargetTexture) {
  85755. this._renderTargetTexture.dispose();
  85756. this._renderTargetTexture = null;
  85757. }
  85758. };
  85759. return ReflectionProbe;
  85760. }());
  85761. BABYLON.ReflectionProbe = ReflectionProbe;
  85762. })(BABYLON || (BABYLON = {}));
  85763. //# sourceMappingURL=babylon.reflectionProbe.js.map
  85764. var BABYLON;
  85765. (function (BABYLON) {
  85766. var Layer = /** @class */ (function () {
  85767. function Layer(name, imgUrl, scene, isBackground, color) {
  85768. this.name = name;
  85769. this.scale = new BABYLON.Vector2(1, 1);
  85770. this.offset = new BABYLON.Vector2(0, 0);
  85771. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  85772. this.layerMask = 0x0FFFFFFF;
  85773. this._vertexBuffers = {};
  85774. // Events
  85775. /**
  85776. * An event triggered when the layer is disposed.
  85777. * @type {BABYLON.Observable}
  85778. */
  85779. this.onDisposeObservable = new BABYLON.Observable();
  85780. /**
  85781. * An event triggered before rendering the scene
  85782. * @type {BABYLON.Observable}
  85783. */
  85784. this.onBeforeRenderObservable = new BABYLON.Observable();
  85785. /**
  85786. * An event triggered after rendering the scene
  85787. * @type {BABYLON.Observable}
  85788. */
  85789. this.onAfterRenderObservable = new BABYLON.Observable();
  85790. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  85791. this.isBackground = isBackground === undefined ? true : isBackground;
  85792. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  85793. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  85794. this._scene.layers.push(this);
  85795. var engine = this._scene.getEngine();
  85796. // VBO
  85797. var vertices = [];
  85798. vertices.push(1, 1);
  85799. vertices.push(-1, 1);
  85800. vertices.push(-1, -1);
  85801. vertices.push(1, -1);
  85802. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85803. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85804. this._createIndexBuffer();
  85805. // Effects
  85806. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  85807. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  85808. }
  85809. Object.defineProperty(Layer.prototype, "onDispose", {
  85810. set: function (callback) {
  85811. if (this._onDisposeObserver) {
  85812. this.onDisposeObservable.remove(this._onDisposeObserver);
  85813. }
  85814. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85815. },
  85816. enumerable: true,
  85817. configurable: true
  85818. });
  85819. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  85820. set: function (callback) {
  85821. if (this._onBeforeRenderObserver) {
  85822. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  85823. }
  85824. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  85825. },
  85826. enumerable: true,
  85827. configurable: true
  85828. });
  85829. Object.defineProperty(Layer.prototype, "onAfterRender", {
  85830. set: function (callback) {
  85831. if (this._onAfterRenderObserver) {
  85832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85833. }
  85834. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  85835. },
  85836. enumerable: true,
  85837. configurable: true
  85838. });
  85839. Layer.prototype._createIndexBuffer = function () {
  85840. var engine = this._scene.getEngine();
  85841. // Indices
  85842. var indices = [];
  85843. indices.push(0);
  85844. indices.push(1);
  85845. indices.push(2);
  85846. indices.push(0);
  85847. indices.push(2);
  85848. indices.push(3);
  85849. this._indexBuffer = engine.createIndexBuffer(indices);
  85850. };
  85851. Layer.prototype._rebuild = function () {
  85852. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85853. if (vb) {
  85854. vb._rebuild();
  85855. }
  85856. this._createIndexBuffer();
  85857. };
  85858. Layer.prototype.render = function () {
  85859. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  85860. // Check
  85861. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  85862. return;
  85863. var engine = this._scene.getEngine();
  85864. this.onBeforeRenderObservable.notifyObservers(this);
  85865. // Render
  85866. engine.enableEffect(currentEffect);
  85867. engine.setState(false);
  85868. // Texture
  85869. currentEffect.setTexture("textureSampler", this.texture);
  85870. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  85871. // Color
  85872. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  85873. // Scale / offset
  85874. currentEffect.setVector2("offset", this.offset);
  85875. currentEffect.setVector2("scale", this.scale);
  85876. // VBOs
  85877. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85878. // Draw order
  85879. if (!this.alphaTest) {
  85880. engine.setAlphaMode(this.alphaBlendingMode);
  85881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85882. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85883. }
  85884. else {
  85885. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85886. }
  85887. this.onAfterRenderObservable.notifyObservers(this);
  85888. };
  85889. Layer.prototype.dispose = function () {
  85890. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85891. if (vertexBuffer) {
  85892. vertexBuffer.dispose();
  85893. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85894. }
  85895. if (this._indexBuffer) {
  85896. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85897. this._indexBuffer = null;
  85898. }
  85899. if (this.texture) {
  85900. this.texture.dispose();
  85901. this.texture = null;
  85902. }
  85903. // Remove from scene
  85904. var index = this._scene.layers.indexOf(this);
  85905. this._scene.layers.splice(index, 1);
  85906. // Callback
  85907. this.onDisposeObservable.notifyObservers(this);
  85908. this.onDisposeObservable.clear();
  85909. this.onAfterRenderObservable.clear();
  85910. this.onBeforeRenderObservable.clear();
  85911. };
  85912. return Layer;
  85913. }());
  85914. BABYLON.Layer = Layer;
  85915. })(BABYLON || (BABYLON = {}));
  85916. //# sourceMappingURL=babylon.layer.js.map
  85917. var BABYLON;
  85918. (function (BABYLON) {
  85919. var TextureTools = /** @class */ (function () {
  85920. function TextureTools() {
  85921. }
  85922. /**
  85923. * Uses the GPU to create a copy texture rescaled at a given size
  85924. * @param texture Texture to copy from
  85925. * @param width Desired width
  85926. * @param height Desired height
  85927. * @return Generated texture
  85928. */
  85929. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85930. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85931. var scene = texture.getScene();
  85932. var engine = scene.getEngine();
  85933. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85934. rtt.wrapU = texture.wrapU;
  85935. rtt.wrapV = texture.wrapV;
  85936. rtt.uOffset = texture.uOffset;
  85937. rtt.vOffset = texture.vOffset;
  85938. rtt.uScale = texture.uScale;
  85939. rtt.vScale = texture.vScale;
  85940. rtt.uAng = texture.uAng;
  85941. rtt.vAng = texture.vAng;
  85942. rtt.wAng = texture.wAng;
  85943. rtt.coordinatesIndex = texture.coordinatesIndex;
  85944. rtt.level = texture.level;
  85945. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85946. rtt._texture.isReady = false;
  85947. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85948. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85949. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85950. passPostProcess.getEffect().executeWhenCompiled(function () {
  85951. passPostProcess.onApply = function (effect) {
  85952. effect.setTexture("textureSampler", texture);
  85953. };
  85954. var internalTexture = rtt.getInternalTexture();
  85955. if (internalTexture) {
  85956. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85957. engine.unBindFramebuffer(internalTexture);
  85958. rtt.disposeFramebufferObjects();
  85959. passPostProcess.dispose();
  85960. internalTexture.isReady = true;
  85961. }
  85962. });
  85963. return rtt;
  85964. };
  85965. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85966. if (!scene._environmentBRDFTexture) {
  85967. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85968. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85969. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85970. scene._environmentBRDFTexture = texture;
  85971. }
  85972. return scene._environmentBRDFTexture;
  85973. };
  85974. 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=";
  85975. return TextureTools;
  85976. }());
  85977. BABYLON.TextureTools = TextureTools;
  85978. })(BABYLON || (BABYLON = {}));
  85979. //# sourceMappingURL=babylon.textureTools.js.map
  85980. var BABYLON;
  85981. (function (BABYLON) {
  85982. var FramingBehavior = /** @class */ (function () {
  85983. function FramingBehavior() {
  85984. this._mode = FramingBehavior.FitFrustumSidesMode;
  85985. this._radiusScale = 1.0;
  85986. this._positionScale = 0.5;
  85987. this._defaultElevation = 0.3;
  85988. this._elevationReturnTime = 1500;
  85989. this._elevationReturnWaitTime = 1000;
  85990. this._zoomStopsAnimation = false;
  85991. this._framingTime = 1500;
  85992. this._isPointerDown = false;
  85993. this._lastInteractionTime = -Infinity;
  85994. // Framing control
  85995. this._animatables = new Array();
  85996. this._betaIsAnimating = false;
  85997. }
  85998. Object.defineProperty(FramingBehavior.prototype, "name", {
  85999. get: function () {
  86000. return "Framing";
  86001. },
  86002. enumerable: true,
  86003. configurable: true
  86004. });
  86005. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86006. /**
  86007. * Gets current mode used by the behavior.
  86008. */
  86009. get: function () {
  86010. return this._mode;
  86011. },
  86012. /**
  86013. * Sets the current mode used by the behavior
  86014. */
  86015. set: function (mode) {
  86016. this._mode = mode;
  86017. },
  86018. enumerable: true,
  86019. configurable: true
  86020. });
  86021. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86022. /**
  86023. * Gets the scale applied to the radius
  86024. */
  86025. get: function () {
  86026. return this._radiusScale;
  86027. },
  86028. /**
  86029. * Sets the scale applied to the radius (1 by default)
  86030. */
  86031. set: function (radius) {
  86032. this._radiusScale = radius;
  86033. },
  86034. enumerable: true,
  86035. configurable: true
  86036. });
  86037. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86038. /**
  86039. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86040. */
  86041. get: function () {
  86042. return this._positionScale;
  86043. },
  86044. /**
  86045. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86046. */
  86047. set: function (scale) {
  86048. this._positionScale = scale;
  86049. },
  86050. enumerable: true,
  86051. configurable: true
  86052. });
  86053. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86054. /**
  86055. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86056. * behaviour is triggered, in radians.
  86057. */
  86058. get: function () {
  86059. return this._defaultElevation;
  86060. },
  86061. /**
  86062. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86063. * behaviour is triggered, in radians.
  86064. */
  86065. set: function (elevation) {
  86066. this._defaultElevation = elevation;
  86067. },
  86068. enumerable: true,
  86069. configurable: true
  86070. });
  86071. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86072. /**
  86073. * Gets the time (in milliseconds) taken to return to the default beta position.
  86074. * Negative value indicates camera should not return to default.
  86075. */
  86076. get: function () {
  86077. return this._elevationReturnTime;
  86078. },
  86079. /**
  86080. * Sets the time (in milliseconds) taken to return to the default beta position.
  86081. * Negative value indicates camera should not return to default.
  86082. */
  86083. set: function (speed) {
  86084. this._elevationReturnTime = speed;
  86085. },
  86086. enumerable: true,
  86087. configurable: true
  86088. });
  86089. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86090. /**
  86091. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86092. */
  86093. get: function () {
  86094. return this._elevationReturnWaitTime;
  86095. },
  86096. /**
  86097. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86098. */
  86099. set: function (time) {
  86100. this._elevationReturnWaitTime = time;
  86101. },
  86102. enumerable: true,
  86103. configurable: true
  86104. });
  86105. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86106. /**
  86107. * Gets the flag that indicates if user zooming should stop animation.
  86108. */
  86109. get: function () {
  86110. return this._zoomStopsAnimation;
  86111. },
  86112. /**
  86113. * Sets the flag that indicates if user zooming should stop animation.
  86114. */
  86115. set: function (flag) {
  86116. this._zoomStopsAnimation = flag;
  86117. },
  86118. enumerable: true,
  86119. configurable: true
  86120. });
  86121. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86122. /**
  86123. * Gets the transition time when framing the mesh, in milliseconds
  86124. */
  86125. get: function () {
  86126. return this._framingTime;
  86127. },
  86128. /**
  86129. * Sets the transition time when framing the mesh, in milliseconds
  86130. */
  86131. set: function (time) {
  86132. this._framingTime = time;
  86133. },
  86134. enumerable: true,
  86135. configurable: true
  86136. });
  86137. FramingBehavior.prototype.init = function () {
  86138. // Do notihng
  86139. };
  86140. FramingBehavior.prototype.attach = function (camera) {
  86141. var _this = this;
  86142. this._attachedCamera = camera;
  86143. var scene = this._attachedCamera.getScene();
  86144. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86145. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86146. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86147. _this._isPointerDown = true;
  86148. return;
  86149. }
  86150. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86151. _this._isPointerDown = false;
  86152. }
  86153. });
  86154. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86155. if (mesh) {
  86156. _this.zoomOnMesh(mesh);
  86157. }
  86158. });
  86159. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86160. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86161. _this._applyUserInteraction();
  86162. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86163. // back to the default position after a given timeout
  86164. _this._maintainCameraAboveGround();
  86165. });
  86166. };
  86167. FramingBehavior.prototype.detach = function () {
  86168. if (!this._attachedCamera) {
  86169. return;
  86170. }
  86171. var scene = this._attachedCamera.getScene();
  86172. if (this._onPrePointerObservableObserver) {
  86173. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86174. }
  86175. if (this._onAfterCheckInputsObserver) {
  86176. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86177. }
  86178. if (this._onMeshTargetChangedObserver) {
  86179. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86180. }
  86181. this._attachedCamera = null;
  86182. };
  86183. /**
  86184. * Targets the given mesh and updates zoom level accordingly.
  86185. * @param mesh The mesh to target.
  86186. * @param radius Optional. If a cached radius position already exists, overrides default.
  86187. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86188. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86189. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86190. */
  86191. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86192. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86193. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86194. mesh.computeWorldMatrix(true);
  86195. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86196. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86197. };
  86198. /**
  86199. * Targets the given mesh with its children and updates zoom level accordingly.
  86200. * @param mesh The mesh to target.
  86201. * @param radius Optional. If a cached radius position already exists, overrides default.
  86202. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86203. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86204. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86205. */
  86206. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86207. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86208. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86209. mesh.computeWorldMatrix(true);
  86210. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86211. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86212. };
  86213. /**
  86214. * Targets the given meshes with their children and updates zoom level accordingly.
  86215. * @param meshes The mesh to target.
  86216. * @param radius Optional. If a cached radius position already exists, overrides default.
  86217. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86218. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86219. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86220. */
  86221. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86222. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86223. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86224. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86225. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86226. for (var i = 0; i < meshes.length; i++) {
  86227. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86228. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86229. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86230. }
  86231. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86232. };
  86233. /**
  86234. * Targets the given mesh and updates zoom level accordingly.
  86235. * @param mesh The mesh to target.
  86236. * @param radius Optional. If a cached radius position already exists, overrides default.
  86237. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86238. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86239. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86240. */
  86241. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86242. var _this = this;
  86243. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86244. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86245. var zoomTarget;
  86246. if (!this._attachedCamera) {
  86247. return;
  86248. }
  86249. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86250. var bottom = minimumWorld.y;
  86251. var top = maximumWorld.y;
  86252. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86253. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86254. if (focusOnOriginXZ) {
  86255. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86256. }
  86257. else {
  86258. var centerWorld = minimumWorld.add(radiusWorld);
  86259. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86260. }
  86261. if (!this._vectorTransition) {
  86262. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86263. }
  86264. this._betaIsAnimating = true;
  86265. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86266. if (animatable) {
  86267. this._animatables.push(animatable);
  86268. }
  86269. // sets the radius and lower radius bounds
  86270. // Small delta ensures camera is not always at lower zoom limit.
  86271. var radius = 0;
  86272. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86273. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86274. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86275. radius = position;
  86276. }
  86277. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86278. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86279. if (this._attachedCamera.lowerRadiusLimit === null) {
  86280. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86281. }
  86282. }
  86283. // Set sensibilities
  86284. var extend = maximumWorld.subtract(minimumWorld).length();
  86285. this._attachedCamera.panningSensibility = 5000 / extend;
  86286. this._attachedCamera.wheelPrecision = 100 / radius;
  86287. // transition to new radius
  86288. if (!this._radiusTransition) {
  86289. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86290. }
  86291. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86292. if (onAnimationEnd) {
  86293. onAnimationEnd();
  86294. }
  86295. if (_this._attachedCamera) {
  86296. _this._attachedCamera.storeState();
  86297. }
  86298. });
  86299. if (animatable) {
  86300. this._animatables.push(animatable);
  86301. }
  86302. };
  86303. /**
  86304. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86305. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86306. * frustum width.
  86307. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86308. * to fully enclose the mesh in the viewing frustum.
  86309. */
  86310. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86311. var size = maximumWorld.subtract(minimumWorld);
  86312. var boxVectorGlobalDiagonal = size.length();
  86313. var frustumSlope = this._getFrustumSlope();
  86314. // Formula for setting distance
  86315. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86316. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86317. // Horizon distance
  86318. var radius = radiusWithoutFraming * this._radiusScale;
  86319. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86320. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86321. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86322. var camera = this._attachedCamera;
  86323. if (!camera) {
  86324. return 0;
  86325. }
  86326. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86327. // Don't exceed the requested limit
  86328. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86329. }
  86330. // Don't exceed the upper radius limit
  86331. if (camera.upperRadiusLimit) {
  86332. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86333. }
  86334. return distance;
  86335. };
  86336. /**
  86337. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86338. * is automatically returned to its default position (expected to be above ground plane).
  86339. */
  86340. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86341. var _this = this;
  86342. if (this._elevationReturnTime < 0) {
  86343. return;
  86344. }
  86345. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86346. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86347. var limitBeta = Math.PI * 0.5;
  86348. // Bring the camera back up if below the ground plane
  86349. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86350. this._betaIsAnimating = true;
  86351. //Transition to new position
  86352. this.stopAllAnimations();
  86353. if (!this._betaTransition) {
  86354. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86355. }
  86356. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86357. _this._clearAnimationLocks();
  86358. _this.stopAllAnimations();
  86359. });
  86360. if (animatabe) {
  86361. this._animatables.push(animatabe);
  86362. }
  86363. }
  86364. };
  86365. /**
  86366. * Returns the frustum slope based on the canvas ratio and camera FOV
  86367. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86368. */
  86369. FramingBehavior.prototype._getFrustumSlope = function () {
  86370. // Calculate the viewport ratio
  86371. // Aspect Ratio is Height/Width.
  86372. var camera = this._attachedCamera;
  86373. if (!camera) {
  86374. return BABYLON.Vector2.Zero();
  86375. }
  86376. var engine = camera.getScene().getEngine();
  86377. var aspectRatio = engine.getAspectRatio(camera);
  86378. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86379. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86380. var frustumSlopeY = Math.tan(camera.fov / 2);
  86381. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86382. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86383. // along the forward vector.
  86384. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86385. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86386. };
  86387. /**
  86388. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86389. */
  86390. FramingBehavior.prototype._clearAnimationLocks = function () {
  86391. this._betaIsAnimating = false;
  86392. };
  86393. /**
  86394. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86395. */
  86396. FramingBehavior.prototype._applyUserInteraction = function () {
  86397. if (this.isUserIsMoving) {
  86398. this._lastInteractionTime = BABYLON.Tools.Now;
  86399. this.stopAllAnimations();
  86400. this._clearAnimationLocks();
  86401. }
  86402. };
  86403. /**
  86404. * Stops and removes all animations that have been applied to the camera
  86405. */
  86406. FramingBehavior.prototype.stopAllAnimations = function () {
  86407. if (this._attachedCamera) {
  86408. this._attachedCamera.animations = [];
  86409. }
  86410. while (this._animatables.length) {
  86411. if (this._animatables[0]) {
  86412. this._animatables[0].onAnimationEnd = null;
  86413. this._animatables[0].stop();
  86414. }
  86415. this._animatables.shift();
  86416. }
  86417. };
  86418. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86419. /**
  86420. * Gets a value indicating if the user is moving the camera
  86421. */
  86422. get: function () {
  86423. if (!this._attachedCamera) {
  86424. return false;
  86425. }
  86426. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86427. this._attachedCamera.inertialBetaOffset !== 0 ||
  86428. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86429. this._attachedCamera.inertialPanningX !== 0 ||
  86430. this._attachedCamera.inertialPanningY !== 0 ||
  86431. this._isPointerDown;
  86432. },
  86433. enumerable: true,
  86434. configurable: true
  86435. });
  86436. /**
  86437. * The easing function used by animations
  86438. */
  86439. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86440. /**
  86441. * The easing mode used by animations
  86442. */
  86443. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86444. // Statics
  86445. /**
  86446. * The camera can move all the way towards the mesh.
  86447. */
  86448. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86449. /**
  86450. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86451. */
  86452. FramingBehavior.FitFrustumSidesMode = 1;
  86453. return FramingBehavior;
  86454. }());
  86455. BABYLON.FramingBehavior = FramingBehavior;
  86456. })(BABYLON || (BABYLON = {}));
  86457. //# sourceMappingURL=babylon.framingBehavior.js.map
  86458. var BABYLON;
  86459. (function (BABYLON) {
  86460. /**
  86461. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86462. */
  86463. var BouncingBehavior = /** @class */ (function () {
  86464. function BouncingBehavior() {
  86465. /**
  86466. * The duration of the animation, in milliseconds
  86467. */
  86468. this.transitionDuration = 450;
  86469. /**
  86470. * Length of the distance animated by the transition when lower radius is reached
  86471. */
  86472. this.lowerRadiusTransitionRange = 2;
  86473. /**
  86474. * Length of the distance animated by the transition when upper radius is reached
  86475. */
  86476. this.upperRadiusTransitionRange = -2;
  86477. this._autoTransitionRange = false;
  86478. // Animations
  86479. this._radiusIsAnimating = false;
  86480. this._radiusBounceTransition = null;
  86481. this._animatables = new Array();
  86482. }
  86483. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86484. get: function () {
  86485. return "Bouncing";
  86486. },
  86487. enumerable: true,
  86488. configurable: true
  86489. });
  86490. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86491. /**
  86492. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86493. */
  86494. get: function () {
  86495. return this._autoTransitionRange;
  86496. },
  86497. /**
  86498. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86499. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86500. */
  86501. set: function (value) {
  86502. var _this = this;
  86503. if (this._autoTransitionRange === value) {
  86504. return;
  86505. }
  86506. this._autoTransitionRange = value;
  86507. var camera = this._attachedCamera;
  86508. if (!camera) {
  86509. return;
  86510. }
  86511. if (value) {
  86512. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86513. if (!mesh) {
  86514. return;
  86515. }
  86516. mesh.computeWorldMatrix(true);
  86517. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86518. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86519. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86520. });
  86521. }
  86522. else if (this._onMeshTargetChangedObserver) {
  86523. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86524. }
  86525. },
  86526. enumerable: true,
  86527. configurable: true
  86528. });
  86529. BouncingBehavior.prototype.init = function () {
  86530. // Do notihng
  86531. };
  86532. BouncingBehavior.prototype.attach = function (camera) {
  86533. var _this = this;
  86534. this._attachedCamera = camera;
  86535. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86536. if (!_this._attachedCamera) {
  86537. return;
  86538. }
  86539. // Add the bounce animation to the lower radius limit
  86540. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86541. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86542. }
  86543. // Add the bounce animation to the upper radius limit
  86544. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86545. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86546. }
  86547. });
  86548. };
  86549. BouncingBehavior.prototype.detach = function () {
  86550. if (!this._attachedCamera) {
  86551. return;
  86552. }
  86553. if (this._onAfterCheckInputsObserver) {
  86554. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86555. }
  86556. if (this._onMeshTargetChangedObserver) {
  86557. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86558. }
  86559. this._attachedCamera = null;
  86560. };
  86561. /**
  86562. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86563. * @param radiusLimit The limit to check against.
  86564. * @return Bool to indicate if at limit.
  86565. */
  86566. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86567. if (!this._attachedCamera) {
  86568. return false;
  86569. }
  86570. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86571. return true;
  86572. }
  86573. return false;
  86574. };
  86575. /**
  86576. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86577. * @param radiusDelta The delta by which to animate to. Can be negative.
  86578. */
  86579. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86580. var _this = this;
  86581. if (!this._attachedCamera) {
  86582. return;
  86583. }
  86584. if (!this._radiusBounceTransition) {
  86585. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86586. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86587. }
  86588. // Prevent zoom until bounce has completed
  86589. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86590. this._attachedCamera.wheelPrecision = Infinity;
  86591. this._attachedCamera.inertialRadiusOffset = 0;
  86592. // Animate to the radius limit
  86593. this.stopAllAnimations();
  86594. this._radiusIsAnimating = true;
  86595. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86596. if (animatable) {
  86597. this._animatables.push(animatable);
  86598. }
  86599. };
  86600. /**
  86601. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86602. */
  86603. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86604. this._radiusIsAnimating = false;
  86605. if (this._attachedCamera) {
  86606. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86607. }
  86608. };
  86609. /**
  86610. * Stops and removes all animations that have been applied to the camera
  86611. */
  86612. BouncingBehavior.prototype.stopAllAnimations = function () {
  86613. if (this._attachedCamera) {
  86614. this._attachedCamera.animations = [];
  86615. }
  86616. while (this._animatables.length) {
  86617. this._animatables[0].onAnimationEnd = null;
  86618. this._animatables[0].stop();
  86619. this._animatables.shift();
  86620. }
  86621. };
  86622. /**
  86623. * The easing function used by animations
  86624. */
  86625. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86626. /**
  86627. * The easing mode used by animations
  86628. */
  86629. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86630. return BouncingBehavior;
  86631. }());
  86632. BABYLON.BouncingBehavior = BouncingBehavior;
  86633. })(BABYLON || (BABYLON = {}));
  86634. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86635. var BABYLON;
  86636. (function (BABYLON) {
  86637. var AutoRotationBehavior = /** @class */ (function () {
  86638. function AutoRotationBehavior() {
  86639. this._zoomStopsAnimation = false;
  86640. this._idleRotationSpeed = 0.05;
  86641. this._idleRotationWaitTime = 2000;
  86642. this._idleRotationSpinupTime = 2000;
  86643. this._isPointerDown = false;
  86644. this._lastFrameTime = null;
  86645. this._lastInteractionTime = -Infinity;
  86646. this._cameraRotationSpeed = 0;
  86647. this._lastFrameRadius = 0;
  86648. }
  86649. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86650. get: function () {
  86651. return "AutoRotation";
  86652. },
  86653. enumerable: true,
  86654. configurable: true
  86655. });
  86656. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86657. /**
  86658. * Gets the flag that indicates if user zooming should stop animation.
  86659. */
  86660. get: function () {
  86661. return this._zoomStopsAnimation;
  86662. },
  86663. /**
  86664. * Sets the flag that indicates if user zooming should stop animation.
  86665. */
  86666. set: function (flag) {
  86667. this._zoomStopsAnimation = flag;
  86668. },
  86669. enumerable: true,
  86670. configurable: true
  86671. });
  86672. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86673. /**
  86674. * Gets the default speed at which the camera rotates around the model.
  86675. */
  86676. get: function () {
  86677. return this._idleRotationSpeed;
  86678. },
  86679. /**
  86680. * Sets the default speed at which the camera rotates around the model.
  86681. */
  86682. set: function (speed) {
  86683. this._idleRotationSpeed = speed;
  86684. },
  86685. enumerable: true,
  86686. configurable: true
  86687. });
  86688. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  86689. /**
  86690. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  86691. */
  86692. get: function () {
  86693. return this._idleRotationWaitTime;
  86694. },
  86695. /**
  86696. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  86697. */
  86698. set: function (time) {
  86699. this._idleRotationWaitTime = time;
  86700. },
  86701. enumerable: true,
  86702. configurable: true
  86703. });
  86704. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  86705. /**
  86706. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86707. */
  86708. get: function () {
  86709. return this._idleRotationSpinupTime;
  86710. },
  86711. /**
  86712. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86713. */
  86714. set: function (time) {
  86715. this._idleRotationSpinupTime = time;
  86716. },
  86717. enumerable: true,
  86718. configurable: true
  86719. });
  86720. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  86721. /**
  86722. * Gets a value indicating if the camera is currently rotating because of this behavior
  86723. */
  86724. get: function () {
  86725. return Math.abs(this._cameraRotationSpeed) > 0;
  86726. },
  86727. enumerable: true,
  86728. configurable: true
  86729. });
  86730. AutoRotationBehavior.prototype.init = function () {
  86731. // Do notihng
  86732. };
  86733. AutoRotationBehavior.prototype.attach = function (camera) {
  86734. var _this = this;
  86735. this._attachedCamera = camera;
  86736. var scene = this._attachedCamera.getScene();
  86737. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86738. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86739. _this._isPointerDown = true;
  86740. return;
  86741. }
  86742. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86743. _this._isPointerDown = false;
  86744. }
  86745. });
  86746. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86747. var now = BABYLON.Tools.Now;
  86748. var dt = 0;
  86749. if (_this._lastFrameTime != null) {
  86750. dt = now - _this._lastFrameTime;
  86751. }
  86752. _this._lastFrameTime = now;
  86753. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86754. _this._applyUserInteraction();
  86755. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  86756. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  86757. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  86758. // Step camera rotation by rotation speed
  86759. if (_this._attachedCamera) {
  86760. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  86761. }
  86762. });
  86763. };
  86764. AutoRotationBehavior.prototype.detach = function () {
  86765. if (!this._attachedCamera) {
  86766. return;
  86767. }
  86768. var scene = this._attachedCamera.getScene();
  86769. if (this._onPrePointerObservableObserver) {
  86770. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86771. }
  86772. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86773. this._attachedCamera = null;
  86774. };
  86775. /**
  86776. * Returns true if user is scrolling.
  86777. * @return true if user is scrolling.
  86778. */
  86779. AutoRotationBehavior.prototype._userIsZooming = function () {
  86780. if (!this._attachedCamera) {
  86781. return false;
  86782. }
  86783. return this._attachedCamera.inertialRadiusOffset !== 0;
  86784. };
  86785. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  86786. if (!this._attachedCamera) {
  86787. return false;
  86788. }
  86789. var zoomHasHitLimit = false;
  86790. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  86791. zoomHasHitLimit = true;
  86792. }
  86793. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  86794. this._lastFrameRadius = this._attachedCamera.radius;
  86795. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  86796. };
  86797. /**
  86798. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86799. */
  86800. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  86801. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  86802. this._lastInteractionTime = BABYLON.Tools.Now;
  86803. }
  86804. };
  86805. // Tools
  86806. AutoRotationBehavior.prototype._userIsMoving = function () {
  86807. if (!this._attachedCamera) {
  86808. return false;
  86809. }
  86810. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86811. this._attachedCamera.inertialBetaOffset !== 0 ||
  86812. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86813. this._attachedCamera.inertialPanningX !== 0 ||
  86814. this._attachedCamera.inertialPanningY !== 0 ||
  86815. this._isPointerDown;
  86816. };
  86817. return AutoRotationBehavior;
  86818. }());
  86819. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  86820. })(BABYLON || (BABYLON = {}));
  86821. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  86822. var BABYLON;
  86823. (function (BABYLON) {
  86824. /**
  86825. * This class can be used to get instrumentation data from a Babylon engine
  86826. */
  86827. var EngineInstrumentation = /** @class */ (function () {
  86828. function EngineInstrumentation(engine) {
  86829. this.engine = engine;
  86830. this._captureGPUFrameTime = false;
  86831. this._gpuFrameTime = new BABYLON.PerfCounter();
  86832. this._captureShaderCompilationTime = false;
  86833. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86834. // Observers
  86835. this._onBeginFrameObserver = null;
  86836. this._onEndFrameObserver = null;
  86837. this._onBeforeShaderCompilationObserver = null;
  86838. this._onAfterShaderCompilationObserver = null;
  86839. }
  86840. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86841. // Properties
  86842. /**
  86843. * Gets the perf counter used for GPU frame time
  86844. */
  86845. get: function () {
  86846. return this._gpuFrameTime;
  86847. },
  86848. enumerable: true,
  86849. configurable: true
  86850. });
  86851. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86852. /**
  86853. * Gets the GPU frame time capture status
  86854. */
  86855. get: function () {
  86856. return this._captureGPUFrameTime;
  86857. },
  86858. /**
  86859. * Enable or disable the GPU frame time capture
  86860. */
  86861. set: function (value) {
  86862. var _this = this;
  86863. if (value === this._captureGPUFrameTime) {
  86864. return;
  86865. }
  86866. this._captureGPUFrameTime = value;
  86867. if (value) {
  86868. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86869. if (!_this._gpuFrameTimeToken) {
  86870. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86871. }
  86872. });
  86873. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86874. if (!_this._gpuFrameTimeToken) {
  86875. return;
  86876. }
  86877. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86878. if (time > -1) {
  86879. _this._gpuFrameTimeToken = null;
  86880. _this._gpuFrameTime.fetchNewFrame();
  86881. _this._gpuFrameTime.addCount(time, true);
  86882. }
  86883. });
  86884. }
  86885. else {
  86886. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86887. this._onBeginFrameObserver = null;
  86888. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86889. this._onEndFrameObserver = null;
  86890. }
  86891. },
  86892. enumerable: true,
  86893. configurable: true
  86894. });
  86895. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86896. /**
  86897. * Gets the perf counter used for shader compilation time
  86898. */
  86899. get: function () {
  86900. return this._shaderCompilationTime;
  86901. },
  86902. enumerable: true,
  86903. configurable: true
  86904. });
  86905. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86906. /**
  86907. * Gets the shader compilation time capture status
  86908. */
  86909. get: function () {
  86910. return this._captureShaderCompilationTime;
  86911. },
  86912. /**
  86913. * Enable or disable the shader compilation time capture
  86914. */
  86915. set: function (value) {
  86916. var _this = this;
  86917. if (value === this._captureShaderCompilationTime) {
  86918. return;
  86919. }
  86920. this._captureShaderCompilationTime = value;
  86921. if (value) {
  86922. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86923. _this._shaderCompilationTime.fetchNewFrame();
  86924. _this._shaderCompilationTime.beginMonitoring();
  86925. });
  86926. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86927. _this._shaderCompilationTime.endMonitoring();
  86928. });
  86929. }
  86930. else {
  86931. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86932. this._onBeforeShaderCompilationObserver = null;
  86933. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86934. this._onAfterShaderCompilationObserver = null;
  86935. }
  86936. },
  86937. enumerable: true,
  86938. configurable: true
  86939. });
  86940. EngineInstrumentation.prototype.dispose = function () {
  86941. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86942. this._onBeginFrameObserver = null;
  86943. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86944. this._onEndFrameObserver = null;
  86945. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86946. this._onBeforeShaderCompilationObserver = null;
  86947. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86948. this._onAfterShaderCompilationObserver = null;
  86949. this.engine = null;
  86950. };
  86951. return EngineInstrumentation;
  86952. }());
  86953. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86954. })(BABYLON || (BABYLON = {}));
  86955. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86956. var BABYLON;
  86957. (function (BABYLON) {
  86958. /**
  86959. * This class can be used to get instrumentation data from a Babylon engine
  86960. */
  86961. var SceneInstrumentation = /** @class */ (function () {
  86962. function SceneInstrumentation(scene) {
  86963. var _this = this;
  86964. this.scene = scene;
  86965. this._captureActiveMeshesEvaluationTime = false;
  86966. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86967. this._captureRenderTargetsRenderTime = false;
  86968. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86969. this._captureFrameTime = false;
  86970. this._frameTime = new BABYLON.PerfCounter();
  86971. this._captureRenderTime = false;
  86972. this._renderTime = new BABYLON.PerfCounter();
  86973. this._captureInterFrameTime = false;
  86974. this._interFrameTime = new BABYLON.PerfCounter();
  86975. this._captureParticlesRenderTime = false;
  86976. this._particlesRenderTime = new BABYLON.PerfCounter();
  86977. this._captureSpritesRenderTime = false;
  86978. this._spritesRenderTime = new BABYLON.PerfCounter();
  86979. this._capturePhysicsTime = false;
  86980. this._physicsTime = new BABYLON.PerfCounter();
  86981. this._captureAnimationsTime = false;
  86982. this._animationsTime = new BABYLON.PerfCounter();
  86983. // Observers
  86984. this._onBeforeActiveMeshesEvaluationObserver = null;
  86985. this._onAfterActiveMeshesEvaluationObserver = null;
  86986. this._onBeforeRenderTargetsRenderObserver = null;
  86987. this._onAfterRenderTargetsRenderObserver = null;
  86988. this._onAfterRenderObserver = null;
  86989. this._onBeforeDrawPhaseObserver = null;
  86990. this._onAfterDrawPhaseObserver = null;
  86991. this._onBeforeAnimationsObserver = null;
  86992. this._onBeforeParticlesRenderingObserver = null;
  86993. this._onAfterParticlesRenderingObserver = null;
  86994. this._onBeforeSpritesRenderingObserver = null;
  86995. this._onAfterSpritesRenderingObserver = null;
  86996. this._onBeforePhysicsObserver = null;
  86997. this._onAfterPhysicsObserver = null;
  86998. this._onAfterAnimationsObserver = null;
  86999. // Before render
  87000. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87001. if (_this._captureActiveMeshesEvaluationTime) {
  87002. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87003. }
  87004. if (_this._captureRenderTargetsRenderTime) {
  87005. _this._renderTargetsRenderTime.fetchNewFrame();
  87006. }
  87007. if (_this._captureFrameTime) {
  87008. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87009. _this._frameTime.beginMonitoring();
  87010. }
  87011. if (_this._captureInterFrameTime) {
  87012. _this._interFrameTime.endMonitoring();
  87013. }
  87014. if (_this._captureParticlesRenderTime) {
  87015. _this._particlesRenderTime.fetchNewFrame();
  87016. }
  87017. if (_this._captureSpritesRenderTime) {
  87018. _this._spritesRenderTime.fetchNewFrame();
  87019. }
  87020. if (_this._captureAnimationsTime) {
  87021. _this._animationsTime.beginMonitoring();
  87022. }
  87023. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87024. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87025. });
  87026. // After render
  87027. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87028. if (_this._captureFrameTime) {
  87029. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87030. _this._frameTime.endMonitoring();
  87031. }
  87032. if (_this._captureRenderTime) {
  87033. _this._renderTime.endMonitoring(false);
  87034. }
  87035. if (_this._captureInterFrameTime) {
  87036. _this._interFrameTime.beginMonitoring();
  87037. }
  87038. });
  87039. }
  87040. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87041. // Properties
  87042. /**
  87043. * Gets the perf counter used for active meshes evaluation time
  87044. */
  87045. get: function () {
  87046. return this._activeMeshesEvaluationTime;
  87047. },
  87048. enumerable: true,
  87049. configurable: true
  87050. });
  87051. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87052. /**
  87053. * Gets the active meshes evaluation time capture status
  87054. */
  87055. get: function () {
  87056. return this._captureActiveMeshesEvaluationTime;
  87057. },
  87058. /**
  87059. * Enable or disable the active meshes evaluation time capture
  87060. */
  87061. set: function (value) {
  87062. var _this = this;
  87063. if (value === this._captureActiveMeshesEvaluationTime) {
  87064. return;
  87065. }
  87066. this._captureActiveMeshesEvaluationTime = value;
  87067. if (value) {
  87068. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87069. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87070. _this._activeMeshesEvaluationTime.beginMonitoring();
  87071. });
  87072. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87073. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87074. _this._activeMeshesEvaluationTime.endMonitoring();
  87075. });
  87076. }
  87077. else {
  87078. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87079. this._onBeforeActiveMeshesEvaluationObserver = null;
  87080. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87081. this._onAfterActiveMeshesEvaluationObserver = null;
  87082. }
  87083. },
  87084. enumerable: true,
  87085. configurable: true
  87086. });
  87087. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87088. /**
  87089. * Gets the perf counter used for render targets render time
  87090. */
  87091. get: function () {
  87092. return this._renderTargetsRenderTime;
  87093. },
  87094. enumerable: true,
  87095. configurable: true
  87096. });
  87097. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87098. /**
  87099. * Gets the render targets render time capture status
  87100. */
  87101. get: function () {
  87102. return this._captureRenderTargetsRenderTime;
  87103. },
  87104. /**
  87105. * Enable or disable the render targets render time capture
  87106. */
  87107. set: function (value) {
  87108. var _this = this;
  87109. if (value === this._captureRenderTargetsRenderTime) {
  87110. return;
  87111. }
  87112. this._captureRenderTargetsRenderTime = value;
  87113. if (value) {
  87114. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87115. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87116. _this._renderTargetsRenderTime.beginMonitoring();
  87117. });
  87118. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87119. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87120. _this._renderTargetsRenderTime.endMonitoring(false);
  87121. });
  87122. }
  87123. else {
  87124. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87125. this._onBeforeRenderTargetsRenderObserver = null;
  87126. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87127. this._onAfterRenderTargetsRenderObserver = null;
  87128. }
  87129. },
  87130. enumerable: true,
  87131. configurable: true
  87132. });
  87133. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87134. /**
  87135. * Gets the perf counter used for particles render time
  87136. */
  87137. get: function () {
  87138. return this._particlesRenderTime;
  87139. },
  87140. enumerable: true,
  87141. configurable: true
  87142. });
  87143. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87144. /**
  87145. * Gets the particles render time capture status
  87146. */
  87147. get: function () {
  87148. return this._captureParticlesRenderTime;
  87149. },
  87150. /**
  87151. * Enable or disable the particles render time capture
  87152. */
  87153. set: function (value) {
  87154. var _this = this;
  87155. if (value === this._captureParticlesRenderTime) {
  87156. return;
  87157. }
  87158. this._captureParticlesRenderTime = value;
  87159. if (value) {
  87160. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87161. BABYLON.Tools.StartPerformanceCounter("Particles");
  87162. _this._particlesRenderTime.beginMonitoring();
  87163. });
  87164. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87165. BABYLON.Tools.EndPerformanceCounter("Particles");
  87166. _this._particlesRenderTime.endMonitoring(false);
  87167. });
  87168. }
  87169. else {
  87170. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87171. this._onBeforeParticlesRenderingObserver = null;
  87172. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87173. this._onAfterParticlesRenderingObserver = null;
  87174. }
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87180. /**
  87181. * Gets the perf counter used for sprites render time
  87182. */
  87183. get: function () {
  87184. return this._spritesRenderTime;
  87185. },
  87186. enumerable: true,
  87187. configurable: true
  87188. });
  87189. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87190. /**
  87191. * Gets the sprites render time capture status
  87192. */
  87193. get: function () {
  87194. return this._captureSpritesRenderTime;
  87195. },
  87196. /**
  87197. * Enable or disable the sprites render time capture
  87198. */
  87199. set: function (value) {
  87200. var _this = this;
  87201. if (value === this._captureSpritesRenderTime) {
  87202. return;
  87203. }
  87204. this._captureSpritesRenderTime = value;
  87205. if (value) {
  87206. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87207. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87208. _this._spritesRenderTime.beginMonitoring();
  87209. });
  87210. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87211. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87212. _this._spritesRenderTime.endMonitoring(false);
  87213. });
  87214. }
  87215. else {
  87216. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87217. this._onBeforeSpritesRenderingObserver = null;
  87218. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87219. this._onAfterSpritesRenderingObserver = null;
  87220. }
  87221. },
  87222. enumerable: true,
  87223. configurable: true
  87224. });
  87225. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87226. /**
  87227. * Gets the perf counter used for physics time
  87228. */
  87229. get: function () {
  87230. return this._physicsTime;
  87231. },
  87232. enumerable: true,
  87233. configurable: true
  87234. });
  87235. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87236. /**
  87237. * Gets the physics time capture status
  87238. */
  87239. get: function () {
  87240. return this._capturePhysicsTime;
  87241. },
  87242. /**
  87243. * Enable or disable the physics time capture
  87244. */
  87245. set: function (value) {
  87246. var _this = this;
  87247. if (value === this._capturePhysicsTime) {
  87248. return;
  87249. }
  87250. this._capturePhysicsTime = value;
  87251. if (value) {
  87252. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87253. BABYLON.Tools.StartPerformanceCounter("Physics");
  87254. _this._physicsTime.beginMonitoring();
  87255. });
  87256. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87257. BABYLON.Tools.EndPerformanceCounter("Physics");
  87258. _this._physicsTime.endMonitoring();
  87259. });
  87260. }
  87261. else {
  87262. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87263. this._onBeforePhysicsObserver = null;
  87264. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87265. this._onAfterPhysicsObserver = null;
  87266. }
  87267. },
  87268. enumerable: true,
  87269. configurable: true
  87270. });
  87271. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87272. /**
  87273. * Gets the perf counter used for animations time
  87274. */
  87275. get: function () {
  87276. return this._animationsTime;
  87277. },
  87278. enumerable: true,
  87279. configurable: true
  87280. });
  87281. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87282. /**
  87283. * Gets the animations time capture status
  87284. */
  87285. get: function () {
  87286. return this._captureAnimationsTime;
  87287. },
  87288. /**
  87289. * Enable or disable the animations time capture
  87290. */
  87291. set: function (value) {
  87292. var _this = this;
  87293. if (value === this._captureAnimationsTime) {
  87294. return;
  87295. }
  87296. this._captureAnimationsTime = value;
  87297. if (value) {
  87298. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87299. _this._animationsTime.endMonitoring();
  87300. });
  87301. }
  87302. else {
  87303. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87304. this._onAfterAnimationsObserver = null;
  87305. }
  87306. },
  87307. enumerable: true,
  87308. configurable: true
  87309. });
  87310. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87311. /**
  87312. * Gets the perf counter used for frame time capture
  87313. */
  87314. get: function () {
  87315. return this._frameTime;
  87316. },
  87317. enumerable: true,
  87318. configurable: true
  87319. });
  87320. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87321. /**
  87322. * Gets the frame time capture status
  87323. */
  87324. get: function () {
  87325. return this._captureFrameTime;
  87326. },
  87327. /**
  87328. * Enable or disable the frame time capture
  87329. */
  87330. set: function (value) {
  87331. this._captureFrameTime = value;
  87332. },
  87333. enumerable: true,
  87334. configurable: true
  87335. });
  87336. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87337. /**
  87338. * Gets the perf counter used for inter-frames time capture
  87339. */
  87340. get: function () {
  87341. return this._interFrameTime;
  87342. },
  87343. enumerable: true,
  87344. configurable: true
  87345. });
  87346. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87347. /**
  87348. * Gets the inter-frames time capture status
  87349. */
  87350. get: function () {
  87351. return this._captureInterFrameTime;
  87352. },
  87353. /**
  87354. * Enable or disable the inter-frames time capture
  87355. */
  87356. set: function (value) {
  87357. this._captureInterFrameTime = value;
  87358. },
  87359. enumerable: true,
  87360. configurable: true
  87361. });
  87362. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87363. /**
  87364. * Gets the perf counter used for render time capture
  87365. */
  87366. get: function () {
  87367. return this._renderTime;
  87368. },
  87369. enumerable: true,
  87370. configurable: true
  87371. });
  87372. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87373. /**
  87374. * Gets the render time capture status
  87375. */
  87376. get: function () {
  87377. return this._captureRenderTime;
  87378. },
  87379. /**
  87380. * Enable or disable the render time capture
  87381. */
  87382. set: function (value) {
  87383. var _this = this;
  87384. if (value === this._captureRenderTime) {
  87385. return;
  87386. }
  87387. this._captureRenderTime = value;
  87388. if (value) {
  87389. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87390. _this._renderTime.beginMonitoring();
  87391. BABYLON.Tools.StartPerformanceCounter("Main render");
  87392. });
  87393. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87394. _this._renderTime.endMonitoring(false);
  87395. BABYLON.Tools.EndPerformanceCounter("Main render");
  87396. });
  87397. }
  87398. else {
  87399. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87400. this._onBeforeDrawPhaseObserver = null;
  87401. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87402. this._onAfterDrawPhaseObserver = null;
  87403. }
  87404. },
  87405. enumerable: true,
  87406. configurable: true
  87407. });
  87408. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87409. /**
  87410. * Gets the perf counter used for draw calls
  87411. */
  87412. get: function () {
  87413. return this.scene.getEngine()._drawCalls;
  87414. },
  87415. enumerable: true,
  87416. configurable: true
  87417. });
  87418. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87419. /**
  87420. * Gets the perf counter used for texture collisions
  87421. */
  87422. get: function () {
  87423. return this.scene.getEngine()._textureCollisions;
  87424. },
  87425. enumerable: true,
  87426. configurable: true
  87427. });
  87428. SceneInstrumentation.prototype.dispose = function () {
  87429. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87430. this._onAfterRenderObserver = null;
  87431. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87432. this._onBeforeActiveMeshesEvaluationObserver = null;
  87433. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87434. this._onAfterActiveMeshesEvaluationObserver = null;
  87435. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87436. this._onBeforeRenderTargetsRenderObserver = null;
  87437. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87438. this._onAfterRenderTargetsRenderObserver = null;
  87439. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87440. this._onBeforeAnimationsObserver = null;
  87441. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87442. this._onBeforeParticlesRenderingObserver = null;
  87443. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87444. this._onAfterParticlesRenderingObserver = null;
  87445. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87446. this._onBeforeSpritesRenderingObserver = null;
  87447. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87448. this._onAfterSpritesRenderingObserver = null;
  87449. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87450. this._onBeforeDrawPhaseObserver = null;
  87451. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87452. this._onAfterDrawPhaseObserver = null;
  87453. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87454. this._onBeforePhysicsObserver = null;
  87455. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87456. this._onAfterPhysicsObserver = null;
  87457. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87458. this._onAfterAnimationsObserver = null;
  87459. this.scene = null;
  87460. };
  87461. return SceneInstrumentation;
  87462. }());
  87463. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87464. })(BABYLON || (BABYLON = {}));
  87465. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87466. var BABYLON;
  87467. (function (BABYLON) {
  87468. var _TimeToken = /** @class */ (function () {
  87469. function _TimeToken() {
  87470. this._timeElapsedQueryEnded = false;
  87471. }
  87472. return _TimeToken;
  87473. }());
  87474. BABYLON._TimeToken = _TimeToken;
  87475. })(BABYLON || (BABYLON = {}));
  87476. //# sourceMappingURL=babylon.timeToken.js.map
  87477. var BABYLON;
  87478. (function (BABYLON) {
  87479. /**
  87480. * Background material defines definition.
  87481. * @ignore Mainly internal Use
  87482. */
  87483. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  87484. __extends(BackgroundMaterialDefines, _super);
  87485. /**
  87486. * Constructor of the defines.
  87487. */
  87488. function BackgroundMaterialDefines() {
  87489. var _this = _super.call(this) || this;
  87490. /**
  87491. * True if the diffuse texture is in use.
  87492. */
  87493. _this.DIFFUSE = false;
  87494. /**
  87495. * The direct UV channel to use.
  87496. */
  87497. _this.DIFFUSEDIRECTUV = 0;
  87498. /**
  87499. * True if the diffuse texture is in gamma space.
  87500. */
  87501. _this.GAMMADIFFUSE = false;
  87502. /**
  87503. * True if the diffuse texture has opacity in the alpha channel.
  87504. */
  87505. _this.DIFFUSEHASALPHA = false;
  87506. /**
  87507. * True if you want the material to fade to transparent at grazing angle.
  87508. */
  87509. _this.OPACITYFRESNEL = false;
  87510. /**
  87511. * True if an extra blur needs to be added in the reflection.
  87512. */
  87513. _this.REFLECTIONBLUR = false;
  87514. /**
  87515. * True if you want the material to fade to reflection at grazing angle.
  87516. */
  87517. _this.REFLECTIONFRESNEL = false;
  87518. /**
  87519. * True if you want the material to falloff as far as you move away from the scene center.
  87520. */
  87521. _this.REFLECTIONFALLOFF = false;
  87522. /**
  87523. * False if the current Webgl implementation does not support the texture lod extension.
  87524. */
  87525. _this.TEXTURELODSUPPORT = false;
  87526. /**
  87527. * True to ensure the data are premultiplied.
  87528. */
  87529. _this.PREMULTIPLYALPHA = false;
  87530. /**
  87531. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  87532. */
  87533. _this.USERGBCOLOR = false;
  87534. /**
  87535. * True to add noise in order to reduce the banding effect.
  87536. */
  87537. _this.NOISE = false;
  87538. /**
  87539. * is the reflection texture in BGR color scheme?
  87540. * Mainly used to solve a bug in ios10 video tag
  87541. */
  87542. _this.REFLECTIONBGR = false;
  87543. _this.IMAGEPROCESSING = false;
  87544. _this.VIGNETTE = false;
  87545. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87546. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87547. _this.TONEMAPPING = false;
  87548. _this.CONTRAST = false;
  87549. _this.COLORCURVES = false;
  87550. _this.COLORGRADING = false;
  87551. _this.COLORGRADING3D = false;
  87552. _this.SAMPLER3DGREENDEPTH = false;
  87553. _this.SAMPLER3DBGRMAP = false;
  87554. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87555. _this.EXPOSURE = false;
  87556. // Reflection.
  87557. _this.REFLECTION = false;
  87558. _this.REFLECTIONMAP_3D = false;
  87559. _this.REFLECTIONMAP_SPHERICAL = false;
  87560. _this.REFLECTIONMAP_PLANAR = false;
  87561. _this.REFLECTIONMAP_CUBIC = false;
  87562. _this.REFLECTIONMAP_PROJECTION = false;
  87563. _this.REFLECTIONMAP_SKYBOX = false;
  87564. _this.REFLECTIONMAP_EXPLICIT = false;
  87565. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87566. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87567. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87568. _this.INVERTCUBICMAP = false;
  87569. _this.REFLECTIONMAP_OPPOSITEZ = false;
  87570. _this.LODINREFLECTIONALPHA = false;
  87571. _this.GAMMAREFLECTION = false;
  87572. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  87573. // Default BJS.
  87574. _this.MAINUV1 = false;
  87575. _this.MAINUV2 = false;
  87576. _this.UV1 = false;
  87577. _this.UV2 = false;
  87578. _this.CLIPPLANE = false;
  87579. _this.POINTSIZE = false;
  87580. _this.FOG = false;
  87581. _this.NORMAL = false;
  87582. _this.NUM_BONE_INFLUENCERS = 0;
  87583. _this.BonesPerMesh = 0;
  87584. _this.INSTANCES = false;
  87585. _this.SHADOWFLOAT = false;
  87586. _this.rebuild();
  87587. return _this;
  87588. }
  87589. return BackgroundMaterialDefines;
  87590. }(BABYLON.MaterialDefines));
  87591. /**
  87592. * Background material used to create an efficient environement around your scene.
  87593. */
  87594. var BackgroundMaterial = /** @class */ (function (_super) {
  87595. __extends(BackgroundMaterial, _super);
  87596. /**
  87597. * Instantiates a Background Material in the given scene
  87598. * @param name The friendly name of the material
  87599. * @param scene The scene to add the material to
  87600. */
  87601. function BackgroundMaterial(name, scene) {
  87602. var _this = _super.call(this, name, scene) || this;
  87603. /**
  87604. * Key light Color (multiply against the R channel of the environement texture)
  87605. */
  87606. _this.primaryColor = BABYLON.Color3.White();
  87607. /**
  87608. * Key light Level (allowing HDR output of the background)
  87609. */
  87610. _this.primaryLevel = 1;
  87611. /**
  87612. * Secondary light Color (multiply against the G channel of the environement texture)
  87613. */
  87614. _this.secondaryColor = BABYLON.Color3.Gray();
  87615. /**
  87616. * Secondary light Level (allowing HDR output of the background)
  87617. */
  87618. _this.secondaryLevel = 1;
  87619. /**
  87620. * Tertiary light Color (multiply against the B channel of the environement texture)
  87621. */
  87622. _this.tertiaryColor = BABYLON.Color3.Black();
  87623. /**
  87624. * Tertiary light Level (allowing HDR output of the background)
  87625. */
  87626. _this.tertiaryLevel = 1;
  87627. /**
  87628. * Reflection Texture used in the material.
  87629. * Should be author in a specific way for the best result (refer to the documentation).
  87630. */
  87631. _this.reflectionTexture = null;
  87632. /**
  87633. * Reflection Texture level of blur.
  87634. *
  87635. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87636. * texture twice.
  87637. */
  87638. _this.reflectionBlur = 0;
  87639. /**
  87640. * Diffuse Texture used in the material.
  87641. * Should be author in a specific way for the best result (refer to the documentation).
  87642. */
  87643. _this.diffuseTexture = null;
  87644. _this._shadowLights = null;
  87645. /**
  87646. * Specify the list of lights casting shadow on the material.
  87647. * All scene shadow lights will be included if null.
  87648. */
  87649. _this.shadowLights = null;
  87650. /**
  87651. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87652. * soft lighting on the background.
  87653. */
  87654. _this.shadowBlurScale = 1;
  87655. /**
  87656. * Helps adjusting the shadow to a softer level if required.
  87657. * 0 means black shadows and 1 means no shadows.
  87658. */
  87659. _this.shadowLevel = 0;
  87660. /**
  87661. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87662. * It is usually zero but might be interesting to modify according to your setup.
  87663. */
  87664. _this.sceneCenter = BABYLON.Vector3.Zero();
  87665. /**
  87666. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87667. * This helps ensuring a nice transition when the camera goes under the ground.
  87668. */
  87669. _this.opacityFresnel = true;
  87670. /**
  87671. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87672. * This helps adding a mirror texture on the ground.
  87673. */
  87674. _this.reflectionFresnel = false;
  87675. /**
  87676. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87677. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87678. */
  87679. _this.reflectionFalloffDistance = 0.0;
  87680. /**
  87681. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87682. */
  87683. _this.reflectionAmount = 1.0;
  87684. /**
  87685. * This specifies the weight of the reflection at grazing angle.
  87686. */
  87687. _this.reflectionReflectance0 = 0.05;
  87688. /**
  87689. * This specifies the weight of the reflection at a perpendicular point of view.
  87690. */
  87691. _this.reflectionReflectance90 = 0.5;
  87692. /**
  87693. * Helps to directly use the maps channels instead of their level.
  87694. */
  87695. _this.useRGBColor = true;
  87696. /**
  87697. * This helps reducing the banding effect that could occur on the background.
  87698. */
  87699. _this.enableNoise = false;
  87700. _this._fovMultiplier = 1.0;
  87701. /**
  87702. * Enable the FOV adjustment feature controlled by fovMultiplier.
  87703. * @type {boolean}
  87704. */
  87705. _this.useEquirectangularFOV = false;
  87706. _this._maxSimultaneousLights = 4;
  87707. /**
  87708. * Number of Simultaneous lights allowed on the material.
  87709. */
  87710. _this.maxSimultaneousLights = 4;
  87711. /**
  87712. * Keep track of the image processing observer to allow dispose and replace.
  87713. */
  87714. _this._imageProcessingObserver = null;
  87715. /**
  87716. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  87717. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  87718. */
  87719. _this.switchToBGR = false;
  87720. // Temp values kept as cache in the material.
  87721. _this._renderTargets = new BABYLON.SmartArray(16);
  87722. _this._reflectionControls = BABYLON.Vector4.Zero();
  87723. // Setup the default processing configuration to the scene.
  87724. _this._attachImageProcessingConfiguration(null);
  87725. _this.getRenderTargetTextures = function () {
  87726. _this._renderTargets.reset();
  87727. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  87728. _this._renderTargets.push(_this._diffuseTexture);
  87729. }
  87730. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  87731. _this._renderTargets.push(_this._reflectionTexture);
  87732. }
  87733. return _this._renderTargets;
  87734. };
  87735. return _this;
  87736. }
  87737. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  87738. /**
  87739. * Sets the reflection reflectance fresnel values according to the default standard
  87740. * empirically know to work well :-)
  87741. */
  87742. set: function (value) {
  87743. var reflectionWeight = value;
  87744. if (reflectionWeight < 0.5) {
  87745. reflectionWeight = reflectionWeight * 2.0;
  87746. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  87747. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  87748. }
  87749. else {
  87750. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  87751. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  87752. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  87753. }
  87754. },
  87755. enumerable: true,
  87756. configurable: true
  87757. });
  87758. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  87759. /**
  87760. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  87761. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  87762. * Recommended to be keep at 1.0 except for special cases.
  87763. */
  87764. get: function () {
  87765. return this._fovMultiplier;
  87766. },
  87767. set: function (value) {
  87768. if (isNaN(value)) {
  87769. value = 1.0;
  87770. }
  87771. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  87772. },
  87773. enumerable: true,
  87774. configurable: true
  87775. });
  87776. /**
  87777. * Attaches a new image processing configuration to the PBR Material.
  87778. * @param configuration (if null the scene configuration will be use)
  87779. */
  87780. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  87781. var _this = this;
  87782. if (configuration === this._imageProcessingConfiguration) {
  87783. return;
  87784. }
  87785. // Detaches observer.
  87786. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87787. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87788. }
  87789. // Pick the scene configuration if needed.
  87790. if (!configuration) {
  87791. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  87792. }
  87793. else {
  87794. this._imageProcessingConfiguration = configuration;
  87795. }
  87796. // Attaches observer.
  87797. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87798. _this._markAllSubMeshesAsImageProcessingDirty();
  87799. });
  87800. };
  87801. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  87802. /**
  87803. * Gets the image processing configuration used either in this material.
  87804. */
  87805. get: function () {
  87806. return this._imageProcessingConfiguration;
  87807. },
  87808. /**
  87809. * Sets the Default image processing configuration used either in the this material.
  87810. *
  87811. * If sets to null, the scene one is in use.
  87812. */
  87813. set: function (value) {
  87814. this._attachImageProcessingConfiguration(value);
  87815. // Ensure the effect will be rebuilt.
  87816. this._markAllSubMeshesAsTexturesDirty();
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  87822. /**
  87823. * Gets wether the color curves effect is enabled.
  87824. */
  87825. get: function () {
  87826. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87827. },
  87828. /**
  87829. * Sets wether the color curves effect is enabled.
  87830. */
  87831. set: function (value) {
  87832. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87833. },
  87834. enumerable: true,
  87835. configurable: true
  87836. });
  87837. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87838. /**
  87839. * Gets wether the color grading effect is enabled.
  87840. */
  87841. get: function () {
  87842. return this.imageProcessingConfiguration.colorGradingEnabled;
  87843. },
  87844. /**
  87845. * Gets wether the color grading effect is enabled.
  87846. */
  87847. set: function (value) {
  87848. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87849. },
  87850. enumerable: true,
  87851. configurable: true
  87852. });
  87853. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87854. /**
  87855. * Gets wether tonemapping is enabled or not.
  87856. */
  87857. get: function () {
  87858. return this._imageProcessingConfiguration.toneMappingEnabled;
  87859. },
  87860. /**
  87861. * Sets wether tonemapping is enabled or not
  87862. */
  87863. set: function (value) {
  87864. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. ;
  87870. ;
  87871. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87872. /**
  87873. * The camera exposure used on this material.
  87874. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87875. * This corresponds to a photographic exposure.
  87876. */
  87877. get: function () {
  87878. return this._imageProcessingConfiguration.exposure;
  87879. },
  87880. /**
  87881. * The camera exposure used on this material.
  87882. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87883. * This corresponds to a photographic exposure.
  87884. */
  87885. set: function (value) {
  87886. this._imageProcessingConfiguration.exposure = value;
  87887. },
  87888. enumerable: true,
  87889. configurable: true
  87890. });
  87891. ;
  87892. ;
  87893. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87894. /**
  87895. * Gets The camera contrast used on this material.
  87896. */
  87897. get: function () {
  87898. return this._imageProcessingConfiguration.contrast;
  87899. },
  87900. /**
  87901. * Sets The camera contrast used on this material.
  87902. */
  87903. set: function (value) {
  87904. this._imageProcessingConfiguration.contrast = value;
  87905. },
  87906. enumerable: true,
  87907. configurable: true
  87908. });
  87909. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87910. /**
  87911. * Gets the Color Grading 2D Lookup Texture.
  87912. */
  87913. get: function () {
  87914. return this._imageProcessingConfiguration.colorGradingTexture;
  87915. },
  87916. /**
  87917. * Sets the Color Grading 2D Lookup Texture.
  87918. */
  87919. set: function (value) {
  87920. this.imageProcessingConfiguration.colorGradingTexture = value;
  87921. },
  87922. enumerable: true,
  87923. configurable: true
  87924. });
  87925. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87926. /**
  87927. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87928. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87929. * 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;
  87930. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87931. */
  87932. get: function () {
  87933. return this.imageProcessingConfiguration.colorCurves;
  87934. },
  87935. /**
  87936. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87937. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87938. * 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;
  87939. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87940. */
  87941. set: function (value) {
  87942. this.imageProcessingConfiguration.colorCurves = value;
  87943. },
  87944. enumerable: true,
  87945. configurable: true
  87946. });
  87947. /**
  87948. * The entire material has been created in order to prevent overdraw.
  87949. * @returns false
  87950. */
  87951. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87952. return true;
  87953. };
  87954. /**
  87955. * The entire material has been created in order to prevent overdraw.
  87956. * @returns true if blending is enable
  87957. */
  87958. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87959. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87960. };
  87961. /**
  87962. * Checks wether the material is ready to be rendered for a given mesh.
  87963. * @param mesh The mesh to render
  87964. * @param subMesh The submesh to check against
  87965. * @param useInstances Specify wether or not the material is used with instances
  87966. * @returns true if all the dependencies are ready (Textures, Effects...)
  87967. */
  87968. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87969. var _this = this;
  87970. if (useInstances === void 0) { useInstances = false; }
  87971. if (subMesh.effect && this.isFrozen) {
  87972. if (this._wasPreviouslyReady) {
  87973. return true;
  87974. }
  87975. }
  87976. if (!subMesh._materialDefines) {
  87977. subMesh._materialDefines = new BackgroundMaterialDefines();
  87978. }
  87979. var scene = this.getScene();
  87980. var defines = subMesh._materialDefines;
  87981. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87982. if (defines._renderId === scene.getRenderId()) {
  87983. return true;
  87984. }
  87985. }
  87986. var engine = scene.getEngine();
  87987. // Lights
  87988. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87989. defines._needNormals = true;
  87990. // Textures
  87991. if (defines._areTexturesDirty) {
  87992. defines._needUVs = false;
  87993. if (scene.texturesEnabled) {
  87994. if (scene.getEngine().getCaps().textureLOD) {
  87995. defines.TEXTURELODSUPPORT = true;
  87996. }
  87997. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87998. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87999. return false;
  88000. }
  88001. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88002. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88003. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88004. defines.OPACITYFRESNEL = this._opacityFresnel;
  88005. }
  88006. else {
  88007. defines.DIFFUSE = false;
  88008. defines.DIFFUSEHASALPHA = false;
  88009. defines.GAMMADIFFUSE = false;
  88010. defines.OPACITYFRESNEL = false;
  88011. }
  88012. var reflectionTexture = this._reflectionTexture;
  88013. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88014. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88015. return false;
  88016. }
  88017. defines.REFLECTION = true;
  88018. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88019. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88020. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88021. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88022. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88023. defines.REFLECTIONBGR = this.switchToBGR;
  88024. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88025. defines.INVERTCUBICMAP = true;
  88026. }
  88027. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88028. switch (reflectionTexture.coordinatesMode) {
  88029. case BABYLON.Texture.CUBIC_MODE:
  88030. case BABYLON.Texture.INVCUBIC_MODE:
  88031. defines.REFLECTIONMAP_CUBIC = true;
  88032. break;
  88033. case BABYLON.Texture.EXPLICIT_MODE:
  88034. defines.REFLECTIONMAP_EXPLICIT = true;
  88035. break;
  88036. case BABYLON.Texture.PLANAR_MODE:
  88037. defines.REFLECTIONMAP_PLANAR = true;
  88038. break;
  88039. case BABYLON.Texture.PROJECTION_MODE:
  88040. defines.REFLECTIONMAP_PROJECTION = true;
  88041. break;
  88042. case BABYLON.Texture.SKYBOX_MODE:
  88043. defines.REFLECTIONMAP_SKYBOX = true;
  88044. break;
  88045. case BABYLON.Texture.SPHERICAL_MODE:
  88046. defines.REFLECTIONMAP_SPHERICAL = true;
  88047. break;
  88048. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88049. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88050. break;
  88051. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88052. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88053. break;
  88054. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88055. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88056. break;
  88057. }
  88058. if (this.reflectionFresnel) {
  88059. defines.REFLECTIONFRESNEL = true;
  88060. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88061. this._reflectionControls.x = this.reflectionAmount;
  88062. this._reflectionControls.y = this.reflectionReflectance0;
  88063. this._reflectionControls.z = this.reflectionReflectance90;
  88064. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88065. }
  88066. else {
  88067. defines.REFLECTIONFRESNEL = false;
  88068. defines.REFLECTIONFALLOFF = false;
  88069. }
  88070. }
  88071. else {
  88072. defines.REFLECTION = false;
  88073. defines.REFLECTIONFALLOFF = false;
  88074. defines.REFLECTIONBLUR = false;
  88075. defines.REFLECTIONMAP_3D = false;
  88076. defines.REFLECTIONMAP_SPHERICAL = false;
  88077. defines.REFLECTIONMAP_PLANAR = false;
  88078. defines.REFLECTIONMAP_CUBIC = false;
  88079. defines.REFLECTIONMAP_PROJECTION = false;
  88080. defines.REFLECTIONMAP_SKYBOX = false;
  88081. defines.REFLECTIONMAP_EXPLICIT = false;
  88082. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88083. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88084. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88085. defines.INVERTCUBICMAP = false;
  88086. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88087. defines.LODINREFLECTIONALPHA = false;
  88088. defines.GAMMAREFLECTION = false;
  88089. }
  88090. }
  88091. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88092. defines.USERGBCOLOR = this._useRGBColor;
  88093. defines.NOISE = this._enableNoise;
  88094. }
  88095. if (defines._areImageProcessingDirty) {
  88096. if (!this._imageProcessingConfiguration.isReady()) {
  88097. return false;
  88098. }
  88099. this._imageProcessingConfiguration.prepareDefines(defines);
  88100. }
  88101. // Misc.
  88102. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88103. // Values that need to be evaluated on every frame
  88104. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88105. // Attribs
  88106. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88107. if (mesh) {
  88108. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88109. mesh.createNormals(true);
  88110. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88111. }
  88112. }
  88113. }
  88114. // Get correct effect
  88115. if (defines.isDirty) {
  88116. defines.markAsProcessed();
  88117. scene.resetCachedMaterial();
  88118. // Fallbacks
  88119. var fallbacks = new BABYLON.EffectFallbacks();
  88120. if (defines.FOG) {
  88121. fallbacks.addFallback(0, "FOG");
  88122. }
  88123. if (defines.POINTSIZE) {
  88124. fallbacks.addFallback(1, "POINTSIZE");
  88125. }
  88126. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88127. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88128. fallbacks.addCPUSkinningFallback(0, mesh);
  88129. }
  88130. //Attributes
  88131. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88132. if (defines.NORMAL) {
  88133. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88134. }
  88135. if (defines.UV1) {
  88136. attribs.push(BABYLON.VertexBuffer.UVKind);
  88137. }
  88138. if (defines.UV2) {
  88139. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88140. }
  88141. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88142. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88143. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88144. "vFogInfos", "vFogColor", "pointSize",
  88145. "vClipPlane", "mBones",
  88146. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88147. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88148. "shadowLevel", "alpha",
  88149. "vBackgroundCenter", "vReflectionControl",
  88150. "vDiffuseInfos", "diffuseMatrix",
  88151. ];
  88152. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88153. var uniformBuffers = ["Material", "Scene"];
  88154. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88155. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88156. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88157. uniformsNames: uniforms,
  88158. uniformBuffersNames: uniformBuffers,
  88159. samplers: samplers,
  88160. defines: defines,
  88161. maxSimultaneousLights: this._maxSimultaneousLights
  88162. });
  88163. var onCompiled = function (effect) {
  88164. if (_this.onCompiled) {
  88165. _this.onCompiled(effect);
  88166. }
  88167. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88168. };
  88169. var join = defines.toString();
  88170. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88171. attributes: attribs,
  88172. uniformsNames: uniforms,
  88173. uniformBuffersNames: uniformBuffers,
  88174. samplers: samplers,
  88175. defines: join,
  88176. fallbacks: fallbacks,
  88177. onCompiled: onCompiled,
  88178. onError: this.onError,
  88179. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88180. }, engine), defines);
  88181. this.buildUniformLayout();
  88182. }
  88183. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88184. return false;
  88185. }
  88186. defines._renderId = scene.getRenderId();
  88187. this._wasPreviouslyReady = true;
  88188. return true;
  88189. };
  88190. /**
  88191. * Build the uniform buffer used in the material.
  88192. */
  88193. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88194. // Order is important !
  88195. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88196. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88197. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88198. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88199. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88200. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88201. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88202. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88203. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88204. this._uniformBuffer.addUniform("pointSize", 1);
  88205. this._uniformBuffer.addUniform("shadowLevel", 1);
  88206. this._uniformBuffer.addUniform("alpha", 1);
  88207. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88208. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88209. this._uniformBuffer.create();
  88210. };
  88211. /**
  88212. * Unbind the material.
  88213. */
  88214. BackgroundMaterial.prototype.unbind = function () {
  88215. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88216. this._uniformBuffer.setTexture("diffuseSampler", null);
  88217. }
  88218. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88219. this._uniformBuffer.setTexture("reflectionSampler", null);
  88220. }
  88221. _super.prototype.unbind.call(this);
  88222. };
  88223. /**
  88224. * Bind only the world matrix to the material.
  88225. * @param world The world matrix to bind.
  88226. */
  88227. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88228. this._activeEffect.setMatrix("world", world);
  88229. };
  88230. /**
  88231. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88232. * @param world The world matrix to bind.
  88233. * @param subMesh The submesh to bind for.
  88234. */
  88235. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88236. var scene = this.getScene();
  88237. var defines = subMesh._materialDefines;
  88238. if (!defines) {
  88239. return;
  88240. }
  88241. var effect = subMesh.effect;
  88242. if (!effect) {
  88243. return;
  88244. }
  88245. this._activeEffect = effect;
  88246. // Matrices
  88247. this.bindOnlyWorldMatrix(world);
  88248. // Bones
  88249. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88250. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88251. if (mustRebind) {
  88252. this._uniformBuffer.bindToEffect(effect, "Material");
  88253. this.bindViewProjection(effect);
  88254. var reflectionTexture = this._reflectionTexture;
  88255. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88256. // Texture uniforms
  88257. if (scene.texturesEnabled) {
  88258. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88259. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88260. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88261. }
  88262. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88263. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88264. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88265. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88266. }
  88267. }
  88268. if (this.shadowLevel > 0) {
  88269. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88270. }
  88271. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88272. // Point size
  88273. if (this.pointsCloud) {
  88274. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88275. }
  88276. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88277. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88278. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88279. }
  88280. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88281. // Textures
  88282. if (scene.texturesEnabled) {
  88283. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88284. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88285. }
  88286. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88287. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88288. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88289. }
  88290. else if (!defines.REFLECTIONBLUR) {
  88291. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88292. }
  88293. else {
  88294. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88295. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88296. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88297. }
  88298. if (defines.REFLECTIONFRESNEL) {
  88299. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88300. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88301. }
  88302. }
  88303. }
  88304. // Clip plane
  88305. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88306. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88307. }
  88308. if (mustRebind || !this.isFrozen) {
  88309. if (scene.lightsEnabled) {
  88310. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88311. }
  88312. // View
  88313. this.bindView(effect);
  88314. // Fog
  88315. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88316. // image processing
  88317. this._imageProcessingConfiguration.bind(this._activeEffect);
  88318. }
  88319. this._uniformBuffer.update();
  88320. this._afterBind(mesh);
  88321. };
  88322. /**
  88323. * Dispose the material.
  88324. * @param forceDisposeEffect Force disposal of the associated effect.
  88325. * @param forceDisposeTextures Force disposal of the associated textures.
  88326. */
  88327. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88328. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88329. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88330. if (forceDisposeTextures) {
  88331. if (this.diffuseTexture) {
  88332. this.diffuseTexture.dispose();
  88333. }
  88334. if (this.reflectionTexture) {
  88335. this.reflectionTexture.dispose();
  88336. }
  88337. }
  88338. this._renderTargets.dispose();
  88339. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88340. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88341. }
  88342. _super.prototype.dispose.call(this, forceDisposeEffect);
  88343. };
  88344. /**
  88345. * Clones the material.
  88346. * @param name The cloned name.
  88347. * @returns The cloned material.
  88348. */
  88349. BackgroundMaterial.prototype.clone = function (name) {
  88350. var _this = this;
  88351. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88352. };
  88353. /**
  88354. * Serializes the current material to its JSON representation.
  88355. * @returns The JSON representation.
  88356. */
  88357. BackgroundMaterial.prototype.serialize = function () {
  88358. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88359. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88360. return serializationObject;
  88361. };
  88362. /**
  88363. * Gets the class name of the material
  88364. * @returns "BackgroundMaterial"
  88365. */
  88366. BackgroundMaterial.prototype.getClassName = function () {
  88367. return "BackgroundMaterial";
  88368. };
  88369. /**
  88370. * Parse a JSON input to create back a background material.
  88371. * @param source The JSON data to parse
  88372. * @param scene The scene to create the parsed material in
  88373. * @param rootUrl The root url of the assets the material depends upon
  88374. * @returns the instantiated BackgroundMaterial.
  88375. */
  88376. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88377. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88378. };
  88379. /**
  88380. * Standard reflectance value at parallel view angle.
  88381. */
  88382. BackgroundMaterial.StandardReflectance0 = 0.05;
  88383. /**
  88384. * Standard reflectance value at grazing angle.
  88385. */
  88386. BackgroundMaterial.StandardReflectance90 = 0.5;
  88387. __decorate([
  88388. BABYLON.serializeAsColor3()
  88389. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88390. __decorate([
  88391. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88392. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88393. __decorate([
  88394. BABYLON.serialize()
  88395. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88396. __decorate([
  88397. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88398. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88399. __decorate([
  88400. BABYLON.serializeAsColor3()
  88401. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88402. __decorate([
  88403. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88404. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88405. __decorate([
  88406. BABYLON.serialize()
  88407. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88408. __decorate([
  88409. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88410. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88411. __decorate([
  88412. BABYLON.serializeAsColor3()
  88413. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88414. __decorate([
  88415. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88416. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88417. __decorate([
  88418. BABYLON.serialize()
  88419. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88420. __decorate([
  88421. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88422. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88423. __decorate([
  88424. BABYLON.serializeAsTexture()
  88425. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88426. __decorate([
  88427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88428. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88429. __decorate([
  88430. BABYLON.serialize()
  88431. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88432. __decorate([
  88433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88434. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88435. __decorate([
  88436. BABYLON.serializeAsTexture()
  88437. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88438. __decorate([
  88439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88440. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88441. __decorate([
  88442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88443. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88444. __decorate([
  88445. BABYLON.serialize()
  88446. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88447. __decorate([
  88448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88449. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88450. __decorate([
  88451. BABYLON.serialize()
  88452. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88453. __decorate([
  88454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88455. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88456. __decorate([
  88457. BABYLON.serializeAsVector3()
  88458. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88459. __decorate([
  88460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88461. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88462. __decorate([
  88463. BABYLON.serialize()
  88464. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88465. __decorate([
  88466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88467. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  88468. __decorate([
  88469. BABYLON.serialize()
  88470. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  88471. __decorate([
  88472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88473. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  88474. __decorate([
  88475. BABYLON.serialize()
  88476. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  88477. __decorate([
  88478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88479. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  88480. __decorate([
  88481. BABYLON.serialize()
  88482. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  88483. __decorate([
  88484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88485. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  88486. __decorate([
  88487. BABYLON.serialize()
  88488. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  88489. __decorate([
  88490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88491. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  88492. __decorate([
  88493. BABYLON.serialize()
  88494. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  88495. __decorate([
  88496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88497. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  88498. __decorate([
  88499. BABYLON.serialize()
  88500. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  88501. __decorate([
  88502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88503. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  88504. __decorate([
  88505. BABYLON.serialize()
  88506. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  88507. __decorate([
  88508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88509. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  88510. __decorate([
  88511. BABYLON.serialize()
  88512. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  88513. __decorate([
  88514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88515. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  88516. __decorate([
  88517. BABYLON.serializeAsImageProcessingConfiguration()
  88518. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  88519. return BackgroundMaterial;
  88520. }(BABYLON.PushMaterial));
  88521. BABYLON.BackgroundMaterial = BackgroundMaterial;
  88522. })(BABYLON || (BABYLON = {}));
  88523. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  88524. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88525. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88526. s = arguments[i];
  88527. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88528. t[p] = s[p];
  88529. }
  88530. return t;
  88531. };
  88532. var BABYLON;
  88533. (function (BABYLON) {
  88534. /**
  88535. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  88536. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  88537. * It also helps with the default setup of your imageProcessing configuration.
  88538. */
  88539. var EnvironmentHelper = /** @class */ (function () {
  88540. /**
  88541. * constructor
  88542. * @param options
  88543. * @param scene The scene to add the material to
  88544. */
  88545. function EnvironmentHelper(options, scene) {
  88546. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  88547. this._scene = scene;
  88548. this._setupBackground();
  88549. this._setupImageProcessing();
  88550. }
  88551. /**
  88552. * Creates the default options for the helper.
  88553. */
  88554. EnvironmentHelper._getDefaultOptions = function () {
  88555. return {
  88556. createGround: true,
  88557. groundSize: 15,
  88558. groundTexture: this._groundTextureCDNUrl,
  88559. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88560. groundOpacity: 0.9,
  88561. enableGroundShadow: true,
  88562. groundShadowLevel: 0.5,
  88563. enableGroundMirror: false,
  88564. groundMirrorSizeRatio: 0.3,
  88565. groundMirrorBlurKernel: 64,
  88566. groundMirrorAmount: 1,
  88567. groundMirrorFresnelWeight: 1,
  88568. groundMirrorFallOffDistance: 0,
  88569. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  88570. groundYBias: 0.00001,
  88571. createSkybox: true,
  88572. skyboxSize: 20,
  88573. skyboxTexture: this._skyboxTextureCDNUrl,
  88574. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88575. backgroundYRotation: 0,
  88576. sizeAuto: true,
  88577. rootPosition: BABYLON.Vector3.Zero(),
  88578. setupImageProcessing: true,
  88579. environmentTexture: this._environmentTextureCDNUrl,
  88580. cameraExposure: 0.8,
  88581. cameraContrast: 1.2,
  88582. toneMappingEnabled: true,
  88583. };
  88584. };
  88585. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88586. /**
  88587. * Gets the root mesh created by the helper.
  88588. */
  88589. get: function () {
  88590. return this._rootMesh;
  88591. },
  88592. enumerable: true,
  88593. configurable: true
  88594. });
  88595. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88596. /**
  88597. * Gets the skybox created by the helper.
  88598. */
  88599. get: function () {
  88600. return this._skybox;
  88601. },
  88602. enumerable: true,
  88603. configurable: true
  88604. });
  88605. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88606. /**
  88607. * Gets the skybox texture created by the helper.
  88608. */
  88609. get: function () {
  88610. return this._skyboxTexture;
  88611. },
  88612. enumerable: true,
  88613. configurable: true
  88614. });
  88615. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88616. /**
  88617. * Gets the skybox material created by the helper.
  88618. */
  88619. get: function () {
  88620. return this._skyboxMaterial;
  88621. },
  88622. enumerable: true,
  88623. configurable: true
  88624. });
  88625. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88626. /**
  88627. * Gets the ground mesh created by the helper.
  88628. */
  88629. get: function () {
  88630. return this._ground;
  88631. },
  88632. enumerable: true,
  88633. configurable: true
  88634. });
  88635. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88636. /**
  88637. * Gets the ground texture created by the helper.
  88638. */
  88639. get: function () {
  88640. return this._groundTexture;
  88641. },
  88642. enumerable: true,
  88643. configurable: true
  88644. });
  88645. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88646. /**
  88647. * Gets the ground mirror created by the helper.
  88648. */
  88649. get: function () {
  88650. return this._groundMirror;
  88651. },
  88652. enumerable: true,
  88653. configurable: true
  88654. });
  88655. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88656. /**
  88657. * Gets the ground mirror render list to helps pushing the meshes
  88658. * you wish in the ground reflection.
  88659. */
  88660. get: function () {
  88661. if (this._groundMirror) {
  88662. return this._groundMirror.renderList;
  88663. }
  88664. return null;
  88665. },
  88666. enumerable: true,
  88667. configurable: true
  88668. });
  88669. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88670. /**
  88671. * Gets the ground material created by the helper.
  88672. */
  88673. get: function () {
  88674. return this._groundMaterial;
  88675. },
  88676. enumerable: true,
  88677. configurable: true
  88678. });
  88679. /**
  88680. * Updates the background according to the new options
  88681. * @param options
  88682. */
  88683. EnvironmentHelper.prototype.updateOptions = function (options) {
  88684. var newOptions = __assign({}, this._options, options);
  88685. if (this._ground && !newOptions.createGround) {
  88686. this._ground.dispose();
  88687. this._ground = null;
  88688. }
  88689. if (this._groundMaterial && !newOptions.createGround) {
  88690. this._groundMaterial.dispose();
  88691. this._groundMaterial = null;
  88692. }
  88693. if (this._groundTexture) {
  88694. if (this._options.groundTexture != newOptions.groundTexture) {
  88695. this._groundTexture.dispose();
  88696. this._groundTexture = null;
  88697. }
  88698. }
  88699. if (this._skybox && !newOptions.createSkybox) {
  88700. this._skybox.dispose();
  88701. this._skybox = null;
  88702. }
  88703. if (this._skyboxMaterial && !newOptions.createSkybox) {
  88704. this._skyboxMaterial.dispose();
  88705. this._skyboxMaterial = null;
  88706. }
  88707. if (this._skyboxTexture) {
  88708. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  88709. this._skyboxTexture.dispose();
  88710. this._skyboxTexture = null;
  88711. }
  88712. }
  88713. if (this._groundMirror && !newOptions.enableGroundMirror) {
  88714. this._groundMirror.dispose();
  88715. this._groundMirror = null;
  88716. }
  88717. if (this._scene.environmentTexture) {
  88718. if (this._options.environmentTexture != newOptions.environmentTexture) {
  88719. this._scene.environmentTexture.dispose();
  88720. }
  88721. }
  88722. this._options = newOptions;
  88723. this._setupBackground();
  88724. this._setupImageProcessing();
  88725. };
  88726. /**
  88727. * Sets the primary color of all the available elements.
  88728. * @param color
  88729. */
  88730. EnvironmentHelper.prototype.setMainColor = function (color) {
  88731. if (this.groundMaterial) {
  88732. this.groundMaterial.primaryColor = color;
  88733. }
  88734. if (this.skyboxMaterial) {
  88735. this.skyboxMaterial.primaryColor = color;
  88736. }
  88737. if (this.groundMirror) {
  88738. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  88739. }
  88740. };
  88741. /**
  88742. * Setup the image processing according to the specified options.
  88743. */
  88744. EnvironmentHelper.prototype._setupImageProcessing = function () {
  88745. if (this._options.setupImageProcessing) {
  88746. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  88747. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  88748. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  88749. this._setupEnvironmentTexture();
  88750. }
  88751. };
  88752. /**
  88753. * Setup the environment texture according to the specified options.
  88754. */
  88755. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  88756. if (this._scene.environmentTexture) {
  88757. return;
  88758. }
  88759. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  88760. this._scene.environmentTexture = this._options.environmentTexture;
  88761. return;
  88762. }
  88763. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  88764. this._scene.environmentTexture = environmentTexture;
  88765. };
  88766. /**
  88767. * Setup the background according to the specified options.
  88768. */
  88769. EnvironmentHelper.prototype._setupBackground = function () {
  88770. if (!this._rootMesh) {
  88771. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  88772. }
  88773. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  88774. var sceneSize = this._getSceneSize();
  88775. if (this._options.createGround) {
  88776. this._setupGround(sceneSize);
  88777. this._setupGroundMaterial();
  88778. this._setupGroundDiffuseTexture();
  88779. if (this._options.enableGroundMirror) {
  88780. this._setupGroundMirrorTexture(sceneSize);
  88781. }
  88782. this._setupMirrorInGroundMaterial();
  88783. }
  88784. if (this._options.createSkybox) {
  88785. this._setupSkybox(sceneSize);
  88786. this._setupSkyboxMaterial();
  88787. this._setupSkyboxReflectionTexture();
  88788. }
  88789. this._rootMesh.position.x = sceneSize.rootPosition.x;
  88790. this._rootMesh.position.z = sceneSize.rootPosition.z;
  88791. this._rootMesh.position.y = sceneSize.rootPosition.y;
  88792. };
  88793. /**
  88794. * Get the scene sizes according to the setup.
  88795. */
  88796. EnvironmentHelper.prototype._getSceneSize = function () {
  88797. var _this = this;
  88798. var groundSize = this._options.groundSize;
  88799. var skyboxSize = this._options.skyboxSize;
  88800. var rootPosition = this._options.rootPosition;
  88801. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  88802. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88803. }
  88804. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  88805. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  88806. });
  88807. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  88808. if (this._options.sizeAuto) {
  88809. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  88810. this._scene.activeCamera.upperRadiusLimit) {
  88811. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  88812. skyboxSize = groundSize;
  88813. }
  88814. var sceneDiagonalLenght = sceneDiagonal.length();
  88815. if (sceneDiagonalLenght > groundSize) {
  88816. groundSize = sceneDiagonalLenght * 2;
  88817. skyboxSize = groundSize;
  88818. }
  88819. // 10 % bigger.
  88820. groundSize *= 1.1;
  88821. skyboxSize *= 1.5;
  88822. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  88823. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  88824. }
  88825. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88826. };
  88827. /**
  88828. * Setup the ground according to the specified options.
  88829. */
  88830. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  88831. var _this = this;
  88832. if (!this._ground) {
  88833. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  88834. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88835. this._ground.parent = this._rootMesh;
  88836. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88837. }
  88838. this._ground.receiveShadows = this._options.enableGroundShadow;
  88839. };
  88840. /**
  88841. * Setup the ground material according to the specified options.
  88842. */
  88843. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88844. if (!this._groundMaterial) {
  88845. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88846. }
  88847. this._groundMaterial.alpha = this._options.groundOpacity;
  88848. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88849. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88850. this._groundMaterial.primaryLevel = 1;
  88851. this._groundMaterial.primaryColor = this._options.groundColor;
  88852. this._groundMaterial.secondaryLevel = 0;
  88853. this._groundMaterial.tertiaryLevel = 0;
  88854. this._groundMaterial.useRGBColor = false;
  88855. this._groundMaterial.enableNoise = true;
  88856. if (this._ground) {
  88857. this._ground.material = this._groundMaterial;
  88858. }
  88859. };
  88860. /**
  88861. * Setup the ground diffuse texture according to the specified options.
  88862. */
  88863. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88864. if (!this._groundMaterial) {
  88865. return;
  88866. }
  88867. if (this._groundTexture) {
  88868. return;
  88869. }
  88870. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88871. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88872. return;
  88873. }
  88874. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88875. diffuseTexture.gammaSpace = false;
  88876. diffuseTexture.hasAlpha = true;
  88877. this._groundMaterial.diffuseTexture = diffuseTexture;
  88878. };
  88879. /**
  88880. * Setup the ground mirror texture according to the specified options.
  88881. */
  88882. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88883. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88884. if (!this._groundMirror) {
  88885. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88886. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88887. this._groundMirror.anisotropicFilteringLevel = 1;
  88888. this._groundMirror.wrapU = wrapping;
  88889. this._groundMirror.wrapV = wrapping;
  88890. this._groundMirror.gammaSpace = false;
  88891. if (this._groundMirror.renderList) {
  88892. for (var i = 0; i < this._scene.meshes.length; i++) {
  88893. var mesh = this._scene.meshes[i];
  88894. if (mesh !== this._ground &&
  88895. mesh !== this._skybox &&
  88896. mesh !== this._rootMesh) {
  88897. this._groundMirror.renderList.push(mesh);
  88898. }
  88899. }
  88900. }
  88901. }
  88902. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88903. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88904. };
  88905. /**
  88906. * Setup the ground to receive the mirror texture.
  88907. */
  88908. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88909. if (this._groundMaterial) {
  88910. this._groundMaterial.reflectionTexture = this._groundMirror;
  88911. this._groundMaterial.reflectionFresnel = true;
  88912. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88913. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88914. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88915. }
  88916. };
  88917. /**
  88918. * Setup the skybox according to the specified options.
  88919. */
  88920. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88921. var _this = this;
  88922. if (!this._skybox) {
  88923. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88924. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88925. }
  88926. this._skybox.parent = this._rootMesh;
  88927. };
  88928. /**
  88929. * Setup the skybox material according to the specified options.
  88930. */
  88931. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88932. if (!this._skybox) {
  88933. return;
  88934. }
  88935. if (!this._skyboxMaterial) {
  88936. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88937. }
  88938. this._skyboxMaterial.useRGBColor = false;
  88939. this._skyboxMaterial.primaryLevel = 1;
  88940. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88941. this._skyboxMaterial.secondaryLevel = 0;
  88942. this._skyboxMaterial.tertiaryLevel = 0;
  88943. this._skyboxMaterial.enableNoise = true;
  88944. this._skybox.material = this._skyboxMaterial;
  88945. };
  88946. /**
  88947. * Setup the skybox reflection texture according to the specified options.
  88948. */
  88949. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88950. if (!this._skyboxMaterial) {
  88951. return;
  88952. }
  88953. if (this._skyboxTexture) {
  88954. return;
  88955. }
  88956. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88957. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88958. return;
  88959. }
  88960. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88961. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88962. this._skyboxTexture.gammaSpace = false;
  88963. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88964. };
  88965. /**
  88966. * Dispose all the elements created by the Helper.
  88967. */
  88968. EnvironmentHelper.prototype.dispose = function () {
  88969. if (this._groundMaterial) {
  88970. this._groundMaterial.dispose(true, true);
  88971. }
  88972. if (this._skyboxMaterial) {
  88973. this._skyboxMaterial.dispose(true, true);
  88974. }
  88975. this._rootMesh.dispose(false);
  88976. };
  88977. /**
  88978. * Default ground texture URL.
  88979. */
  88980. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88981. /**
  88982. * Default skybox texture URL.
  88983. */
  88984. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88985. /**
  88986. * Default environment texture URL.
  88987. */
  88988. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88989. return EnvironmentHelper;
  88990. }());
  88991. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88992. })(BABYLON || (BABYLON = {}));
  88993. //# sourceMappingURL=babylon.environmentHelper.js.map
  88994. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88995. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  88996. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88997. var BABYLON;
  88998. (function (BABYLON) {
  88999. var GridMaterialDefines = /** @class */ (function (_super) {
  89000. __extends(GridMaterialDefines, _super);
  89001. function GridMaterialDefines() {
  89002. var _this = _super.call(this) || this;
  89003. _this.TRANSPARENT = false;
  89004. _this.FOG = false;
  89005. _this.PREMULTIPLYALPHA = false;
  89006. _this.rebuild();
  89007. return _this;
  89008. }
  89009. return GridMaterialDefines;
  89010. }(BABYLON.MaterialDefines));
  89011. /**
  89012. * The grid materials allows you to wrap any shape with a grid.
  89013. * Colors are customizable.
  89014. */
  89015. var GridMaterial = /** @class */ (function (_super) {
  89016. __extends(GridMaterial, _super);
  89017. /**
  89018. * constructor
  89019. * @param name The name given to the material in order to identify it afterwards.
  89020. * @param scene The scene the material is used in.
  89021. */
  89022. function GridMaterial(name, scene) {
  89023. var _this = _super.call(this, name, scene) || this;
  89024. /**
  89025. * Main color of the grid (e.g. between lines)
  89026. */
  89027. _this.mainColor = BABYLON.Color3.Black();
  89028. /**
  89029. * Color of the grid lines.
  89030. */
  89031. _this.lineColor = BABYLON.Color3.Teal();
  89032. /**
  89033. * The scale of the grid compared to unit.
  89034. */
  89035. _this.gridRatio = 1.0;
  89036. /**
  89037. * Allows setting an offset for the grid lines.
  89038. */
  89039. _this.gridOffset = BABYLON.Vector3.Zero();
  89040. /**
  89041. * The frequency of thicker lines.
  89042. */
  89043. _this.majorUnitFrequency = 10;
  89044. /**
  89045. * The visibility of minor units in the grid.
  89046. */
  89047. _this.minorUnitVisibility = 0.33;
  89048. /**
  89049. * The grid opacity outside of the lines.
  89050. */
  89051. _this.opacity = 1.0;
  89052. /**
  89053. * Determine RBG output is premultiplied by alpha value.
  89054. */
  89055. _this.preMultiplyAlpha = false;
  89056. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89057. return _this;
  89058. }
  89059. /**
  89060. * Returns wehter or not the grid requires alpha blending.
  89061. */
  89062. GridMaterial.prototype.needAlphaBlending = function () {
  89063. return this.opacity < 1.0;
  89064. };
  89065. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89066. return this.needAlphaBlending();
  89067. };
  89068. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89069. if (this.isFrozen) {
  89070. if (this._wasPreviouslyReady && subMesh.effect) {
  89071. return true;
  89072. }
  89073. }
  89074. if (!subMesh._materialDefines) {
  89075. subMesh._materialDefines = new GridMaterialDefines();
  89076. }
  89077. var defines = subMesh._materialDefines;
  89078. var scene = this.getScene();
  89079. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89080. if (this._renderId === scene.getRenderId()) {
  89081. return true;
  89082. }
  89083. }
  89084. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89085. defines.TRANSPARENT = !defines.TRANSPARENT;
  89086. defines.markAsUnprocessed();
  89087. }
  89088. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89089. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89090. defines.markAsUnprocessed();
  89091. }
  89092. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89093. // Get correct effect
  89094. if (defines.isDirty) {
  89095. defines.markAsProcessed();
  89096. scene.resetCachedMaterial();
  89097. // Attributes
  89098. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89099. // Defines
  89100. var join = defines.toString();
  89101. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89102. }
  89103. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89104. return false;
  89105. }
  89106. this._renderId = scene.getRenderId();
  89107. this._wasPreviouslyReady = true;
  89108. return true;
  89109. };
  89110. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89111. var scene = this.getScene();
  89112. var defines = subMesh._materialDefines;
  89113. if (!defines) {
  89114. return;
  89115. }
  89116. var effect = subMesh.effect;
  89117. if (!effect) {
  89118. return;
  89119. }
  89120. this._activeEffect = effect;
  89121. // Matrices
  89122. this.bindOnlyWorldMatrix(world);
  89123. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89124. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89125. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89126. // Uniforms
  89127. if (this._mustRebind(scene, effect)) {
  89128. this._activeEffect.setColor3("mainColor", this.mainColor);
  89129. this._activeEffect.setColor3("lineColor", this.lineColor);
  89130. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89131. this._gridControl.x = this.gridRatio;
  89132. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89133. this._gridControl.z = this.minorUnitVisibility;
  89134. this._gridControl.w = this.opacity;
  89135. this._activeEffect.setVector4("gridControl", this._gridControl);
  89136. }
  89137. // Fog
  89138. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89139. this._afterBind(mesh, this._activeEffect);
  89140. };
  89141. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89142. _super.prototype.dispose.call(this, forceDisposeEffect);
  89143. };
  89144. GridMaterial.prototype.clone = function (name) {
  89145. var _this = this;
  89146. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89147. };
  89148. GridMaterial.prototype.serialize = function () {
  89149. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89150. serializationObject.customType = "BABYLON.GridMaterial";
  89151. return serializationObject;
  89152. };
  89153. GridMaterial.prototype.getClassName = function () {
  89154. return "GridMaterial";
  89155. };
  89156. GridMaterial.Parse = function (source, scene, rootUrl) {
  89157. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89158. };
  89159. __decorate([
  89160. BABYLON.serializeAsColor3()
  89161. ], GridMaterial.prototype, "mainColor", void 0);
  89162. __decorate([
  89163. BABYLON.serializeAsColor3()
  89164. ], GridMaterial.prototype, "lineColor", void 0);
  89165. __decorate([
  89166. BABYLON.serialize()
  89167. ], GridMaterial.prototype, "gridRatio", void 0);
  89168. __decorate([
  89169. BABYLON.serializeAsColor3()
  89170. ], GridMaterial.prototype, "gridOffset", void 0);
  89171. __decorate([
  89172. BABYLON.serialize()
  89173. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89174. __decorate([
  89175. BABYLON.serialize()
  89176. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89177. __decorate([
  89178. BABYLON.serialize()
  89179. ], GridMaterial.prototype, "opacity", void 0);
  89180. __decorate([
  89181. BABYLON.serialize()
  89182. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89183. return GridMaterial;
  89184. }(BABYLON.PushMaterial));
  89185. BABYLON.GridMaterial = GridMaterial;
  89186. })(BABYLON || (BABYLON = {}));
  89187. //# sourceMappingURL=babylon.gridmaterial.js.map
  89188. 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}";
  89189. 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}";
  89190. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89191. var BABYLON;
  89192. (function (BABYLON) {
  89193. var GLTFLoaderCoordinateSystemMode;
  89194. (function (GLTFLoaderCoordinateSystemMode) {
  89195. /**
  89196. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89197. */
  89198. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89199. /**
  89200. * Sets the useRightHandedSystem flag on the scene.
  89201. */
  89202. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89203. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89204. var GLTFLoaderAnimationStartMode;
  89205. (function (GLTFLoaderAnimationStartMode) {
  89206. /**
  89207. * No animation will start.
  89208. */
  89209. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89210. /**
  89211. * The first animation will start.
  89212. */
  89213. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89214. /**
  89215. * All animations will start.
  89216. */
  89217. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89218. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89219. var GLTFLoaderState;
  89220. (function (GLTFLoaderState) {
  89221. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89222. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89223. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89224. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89225. var GLTFFileLoader = /** @class */ (function () {
  89226. function GLTFFileLoader() {
  89227. // #region Common options
  89228. /**
  89229. * Raised when the asset has been parsed.
  89230. * The data.json property stores the glTF JSON.
  89231. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89232. */
  89233. this.onParsedObservable = new BABYLON.Observable();
  89234. // #endregion
  89235. // #region V2 options
  89236. /**
  89237. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89238. */
  89239. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89240. /**
  89241. * The animation start mode (NONE, FIRST, ALL).
  89242. */
  89243. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89244. /**
  89245. * Set to true to compile materials before raising the success callback.
  89246. */
  89247. this.compileMaterials = false;
  89248. /**
  89249. * Set to true to also compile materials with clip planes.
  89250. */
  89251. this.useClipPlane = false;
  89252. /**
  89253. * Set to true to compile shadow generators before raising the success callback.
  89254. */
  89255. this.compileShadowGenerators = false;
  89256. /**
  89257. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89258. */
  89259. this.onMeshLoadedObservable = new BABYLON.Observable();
  89260. /**
  89261. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89262. */
  89263. this.onTextureLoadedObservable = new BABYLON.Observable();
  89264. /**
  89265. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89266. */
  89267. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89268. /**
  89269. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89270. * For assets with LODs, raised when all of the LODs are complete.
  89271. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89272. */
  89273. this.onCompleteObservable = new BABYLON.Observable();
  89274. /**
  89275. * Raised when the loader is disposed.
  89276. */
  89277. this.onDisposeObservable = new BABYLON.Observable();
  89278. /**
  89279. * Raised after a loader extension is created.
  89280. * Set additional options for a loader extension in this event.
  89281. */
  89282. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89283. // #endregion
  89284. this._loader = null;
  89285. this.name = "gltf";
  89286. this.extensions = {
  89287. ".gltf": { isBinary: false },
  89288. ".glb": { isBinary: true }
  89289. };
  89290. }
  89291. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89292. set: function (callback) {
  89293. if (this._onParsedObserver) {
  89294. this.onParsedObservable.remove(this._onParsedObserver);
  89295. }
  89296. this._onParsedObserver = this.onParsedObservable.add(callback);
  89297. },
  89298. enumerable: true,
  89299. configurable: true
  89300. });
  89301. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89302. set: function (callback) {
  89303. if (this._onMeshLoadedObserver) {
  89304. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89305. }
  89306. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89307. },
  89308. enumerable: true,
  89309. configurable: true
  89310. });
  89311. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89312. set: function (callback) {
  89313. if (this._onTextureLoadedObserver) {
  89314. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89315. }
  89316. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89317. },
  89318. enumerable: true,
  89319. configurable: true
  89320. });
  89321. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89322. set: function (callback) {
  89323. if (this._onMaterialLoadedObserver) {
  89324. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89325. }
  89326. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89327. },
  89328. enumerable: true,
  89329. configurable: true
  89330. });
  89331. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89332. set: function (callback) {
  89333. if (this._onCompleteObserver) {
  89334. this.onCompleteObservable.remove(this._onCompleteObserver);
  89335. }
  89336. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89337. },
  89338. enumerable: true,
  89339. configurable: true
  89340. });
  89341. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89342. set: function (callback) {
  89343. if (this._onDisposeObserver) {
  89344. this.onDisposeObservable.remove(this._onDisposeObserver);
  89345. }
  89346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89347. },
  89348. enumerable: true,
  89349. configurable: true
  89350. });
  89351. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89352. set: function (callback) {
  89353. if (this._onExtensionLoadedObserver) {
  89354. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89355. }
  89356. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89357. },
  89358. enumerable: true,
  89359. configurable: true
  89360. });
  89361. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89362. /**
  89363. * The loader state or null if not active.
  89364. */
  89365. get: function () {
  89366. return this._loader ? this._loader.state : null;
  89367. },
  89368. enumerable: true,
  89369. configurable: true
  89370. });
  89371. /**
  89372. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89373. */
  89374. GLTFFileLoader.prototype.dispose = function () {
  89375. if (this._loader) {
  89376. this._loader.dispose();
  89377. this._loader = null;
  89378. }
  89379. this.onMeshLoadedObservable.clear();
  89380. this.onTextureLoadedObservable.clear();
  89381. this.onMaterialLoadedObservable.clear();
  89382. this.onDisposeObservable.notifyObservers(this);
  89383. this.onDisposeObservable.clear();
  89384. };
  89385. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89386. var _this = this;
  89387. return Promise.resolve().then(function () {
  89388. var loaderData = _this._parse(data);
  89389. _this._loader = _this._getLoader(loaderData);
  89390. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89391. });
  89392. };
  89393. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89394. var _this = this;
  89395. return Promise.resolve().then(function () {
  89396. var loaderData = _this._parse(data);
  89397. _this._loader = _this._getLoader(loaderData);
  89398. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89399. });
  89400. };
  89401. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89402. var _this = this;
  89403. return Promise.resolve().then(function () {
  89404. var loaderData = _this._parse(data);
  89405. _this._loader = _this._getLoader(loaderData);
  89406. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89407. var container = new BABYLON.AssetContainer(scene);
  89408. Array.prototype.push.apply(container.meshes, result.meshes);
  89409. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89410. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89411. container.removeAllFromScene();
  89412. return container;
  89413. });
  89414. });
  89415. };
  89416. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  89417. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  89418. };
  89419. GLTFFileLoader.prototype.createPlugin = function () {
  89420. return new GLTFFileLoader();
  89421. };
  89422. GLTFFileLoader.prototype._parse = function (data) {
  89423. var parsedData;
  89424. if (data instanceof ArrayBuffer) {
  89425. parsedData = GLTFFileLoader._parseBinary(data);
  89426. }
  89427. else {
  89428. parsedData = {
  89429. json: JSON.parse(data),
  89430. bin: null
  89431. };
  89432. }
  89433. this.onParsedObservable.notifyObservers(parsedData);
  89434. this.onParsedObservable.clear();
  89435. return parsedData;
  89436. };
  89437. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  89438. var _this = this;
  89439. var loaderVersion = { major: 2, minor: 0 };
  89440. var asset = loaderData.json.asset || {};
  89441. var version = GLTFFileLoader._parseVersion(asset.version);
  89442. if (!version) {
  89443. throw new Error("Invalid version: " + asset.version);
  89444. }
  89445. if (asset.minVersion !== undefined) {
  89446. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  89447. if (!minVersion) {
  89448. throw new Error("Invalid minimum version: " + asset.minVersion);
  89449. }
  89450. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  89451. throw new Error("Incompatible minimum version: " + asset.minVersion);
  89452. }
  89453. }
  89454. var createLoaders = {
  89455. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  89456. 2: GLTFFileLoader.CreateGLTFLoaderV2
  89457. };
  89458. var createLoader = createLoaders[version.major];
  89459. if (!createLoader) {
  89460. throw new Error("Unsupported version: " + asset.version);
  89461. }
  89462. var loader = createLoader();
  89463. loader.coordinateSystemMode = this.coordinateSystemMode;
  89464. loader.animationStartMode = this.animationStartMode;
  89465. loader.compileMaterials = this.compileMaterials;
  89466. loader.useClipPlane = this.useClipPlane;
  89467. loader.compileShadowGenerators = this.compileShadowGenerators;
  89468. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  89469. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  89470. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  89471. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  89472. loader.onCompleteObservable.add(function () {
  89473. _this.onMeshLoadedObservable.clear();
  89474. _this.onTextureLoadedObservable.clear();
  89475. _this.onMaterialLoadedObservable.clear();
  89476. _this.onCompleteObservable.notifyObservers(_this);
  89477. _this.onCompleteObservable.clear();
  89478. });
  89479. return loader;
  89480. };
  89481. GLTFFileLoader._parseBinary = function (data) {
  89482. var Binary = {
  89483. Magic: 0x46546C67
  89484. };
  89485. var binaryReader = new BinaryReader(data);
  89486. var magic = binaryReader.readUint32();
  89487. if (magic !== Binary.Magic) {
  89488. throw new Error("Unexpected magic: " + magic);
  89489. }
  89490. var version = binaryReader.readUint32();
  89491. switch (version) {
  89492. case 1: return GLTFFileLoader._parseV1(binaryReader);
  89493. case 2: return GLTFFileLoader._parseV2(binaryReader);
  89494. }
  89495. throw new Error("Unsupported version: " + version);
  89496. };
  89497. GLTFFileLoader._parseV1 = function (binaryReader) {
  89498. var ContentFormat = {
  89499. JSON: 0
  89500. };
  89501. var length = binaryReader.readUint32();
  89502. if (length != binaryReader.getLength()) {
  89503. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89504. }
  89505. var contentLength = binaryReader.readUint32();
  89506. var contentFormat = binaryReader.readUint32();
  89507. var content;
  89508. switch (contentFormat) {
  89509. case ContentFormat.JSON: {
  89510. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  89511. break;
  89512. }
  89513. default: {
  89514. throw new Error("Unexpected content format: " + contentFormat);
  89515. }
  89516. }
  89517. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  89518. var body = binaryReader.readUint8Array(bytesRemaining);
  89519. return {
  89520. json: content,
  89521. bin: body
  89522. };
  89523. };
  89524. GLTFFileLoader._parseV2 = function (binaryReader) {
  89525. var ChunkFormat = {
  89526. JSON: 0x4E4F534A,
  89527. BIN: 0x004E4942
  89528. };
  89529. var length = binaryReader.readUint32();
  89530. if (length !== binaryReader.getLength()) {
  89531. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89532. }
  89533. // JSON chunk
  89534. var chunkLength = binaryReader.readUint32();
  89535. var chunkFormat = binaryReader.readUint32();
  89536. if (chunkFormat !== ChunkFormat.JSON) {
  89537. throw new Error("First chunk format is not JSON");
  89538. }
  89539. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  89540. // Look for BIN chunk
  89541. var bin = null;
  89542. while (binaryReader.getPosition() < binaryReader.getLength()) {
  89543. var chunkLength_1 = binaryReader.readUint32();
  89544. var chunkFormat_1 = binaryReader.readUint32();
  89545. switch (chunkFormat_1) {
  89546. case ChunkFormat.JSON: {
  89547. throw new Error("Unexpected JSON chunk");
  89548. }
  89549. case ChunkFormat.BIN: {
  89550. bin = binaryReader.readUint8Array(chunkLength_1);
  89551. break;
  89552. }
  89553. default: {
  89554. // ignore unrecognized chunkFormat
  89555. binaryReader.skipBytes(chunkLength_1);
  89556. break;
  89557. }
  89558. }
  89559. }
  89560. return {
  89561. json: json,
  89562. bin: bin
  89563. };
  89564. };
  89565. GLTFFileLoader._parseVersion = function (version) {
  89566. if (version === "1.0" || version === "1.0.1") {
  89567. return {
  89568. major: 1,
  89569. minor: 0
  89570. };
  89571. }
  89572. var match = (version + "").match(/^(\d+)\.(\d+)/);
  89573. if (!match) {
  89574. return null;
  89575. }
  89576. return {
  89577. major: parseInt(match[1]),
  89578. minor: parseInt(match[2])
  89579. };
  89580. };
  89581. GLTFFileLoader._compareVersion = function (a, b) {
  89582. if (a.major > b.major)
  89583. return 1;
  89584. if (a.major < b.major)
  89585. return -1;
  89586. if (a.minor > b.minor)
  89587. return 1;
  89588. if (a.minor < b.minor)
  89589. return -1;
  89590. return 0;
  89591. };
  89592. GLTFFileLoader._decodeBufferToText = function (buffer) {
  89593. var result = "";
  89594. var length = buffer.byteLength;
  89595. for (var i = 0; i < length; i++) {
  89596. result += String.fromCharCode(buffer[i]);
  89597. }
  89598. return result;
  89599. };
  89600. // #endregion
  89601. // #region V1 options
  89602. GLTFFileLoader.IncrementalLoading = true;
  89603. GLTFFileLoader.HomogeneousCoordinates = false;
  89604. return GLTFFileLoader;
  89605. }());
  89606. BABYLON.GLTFFileLoader = GLTFFileLoader;
  89607. var BinaryReader = /** @class */ (function () {
  89608. function BinaryReader(arrayBuffer) {
  89609. this._arrayBuffer = arrayBuffer;
  89610. this._dataView = new DataView(arrayBuffer);
  89611. this._byteOffset = 0;
  89612. }
  89613. BinaryReader.prototype.getPosition = function () {
  89614. return this._byteOffset;
  89615. };
  89616. BinaryReader.prototype.getLength = function () {
  89617. return this._arrayBuffer.byteLength;
  89618. };
  89619. BinaryReader.prototype.readUint32 = function () {
  89620. var value = this._dataView.getUint32(this._byteOffset, true);
  89621. this._byteOffset += 4;
  89622. return value;
  89623. };
  89624. BinaryReader.prototype.readUint8Array = function (length) {
  89625. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  89626. this._byteOffset += length;
  89627. return value;
  89628. };
  89629. BinaryReader.prototype.skipBytes = function (length) {
  89630. this._byteOffset += length;
  89631. };
  89632. return BinaryReader;
  89633. }());
  89634. if (BABYLON.SceneLoader) {
  89635. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  89636. }
  89637. })(BABYLON || (BABYLON = {}));
  89638. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  89639. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89640. var BABYLON;
  89641. (function (BABYLON) {
  89642. var GLTF1;
  89643. (function (GLTF1) {
  89644. /**
  89645. * Enums
  89646. */
  89647. var EComponentType;
  89648. (function (EComponentType) {
  89649. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89650. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89651. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89652. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89653. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89654. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  89655. var EShaderType;
  89656. (function (EShaderType) {
  89657. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  89658. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  89659. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  89660. var EParameterType;
  89661. (function (EParameterType) {
  89662. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  89663. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89664. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  89665. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89666. EParameterType[EParameterType["INT"] = 5124] = "INT";
  89667. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  89668. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  89669. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  89670. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  89671. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  89672. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  89673. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  89674. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  89675. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  89676. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  89677. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  89678. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  89679. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  89680. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  89681. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  89682. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  89683. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  89684. var ETextureWrapMode;
  89685. (function (ETextureWrapMode) {
  89686. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  89687. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  89688. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  89689. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  89690. var ETextureFilterType;
  89691. (function (ETextureFilterType) {
  89692. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  89693. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  89694. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  89695. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  89696. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  89697. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  89698. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  89699. var ETextureFormat;
  89700. (function (ETextureFormat) {
  89701. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  89702. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  89703. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  89704. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  89705. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  89706. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  89707. var ECullingType;
  89708. (function (ECullingType) {
  89709. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  89710. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  89711. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  89712. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  89713. var EBlendingFunction;
  89714. (function (EBlendingFunction) {
  89715. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  89716. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  89717. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  89718. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  89719. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  89720. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  89721. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  89722. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  89723. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  89724. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  89725. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  89726. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  89727. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  89728. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  89729. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  89730. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  89731. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89732. })(BABYLON || (BABYLON = {}));
  89733. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  89734. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89735. var BABYLON;
  89736. (function (BABYLON) {
  89737. var GLTF1;
  89738. (function (GLTF1) {
  89739. /**
  89740. * Tokenizer. Used for shaders compatibility
  89741. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  89742. */
  89743. var ETokenType;
  89744. (function (ETokenType) {
  89745. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  89746. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  89747. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  89748. })(ETokenType || (ETokenType = {}));
  89749. var Tokenizer = /** @class */ (function () {
  89750. function Tokenizer(toParse) {
  89751. this._pos = 0;
  89752. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  89753. this._toParse = toParse;
  89754. this._maxPos = toParse.length;
  89755. }
  89756. Tokenizer.prototype.getNextToken = function () {
  89757. if (this.isEnd())
  89758. return ETokenType.END_OF_INPUT;
  89759. this.currentString = this.read();
  89760. this.currentToken = ETokenType.UNKNOWN;
  89761. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  89762. this.currentToken = ETokenType.IDENTIFIER;
  89763. this.currentIdentifier = this.currentString;
  89764. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  89765. this.currentIdentifier += this.currentString;
  89766. this.forward();
  89767. }
  89768. }
  89769. return this.currentToken;
  89770. };
  89771. Tokenizer.prototype.peek = function () {
  89772. return this._toParse[this._pos];
  89773. };
  89774. Tokenizer.prototype.read = function () {
  89775. return this._toParse[this._pos++];
  89776. };
  89777. Tokenizer.prototype.forward = function () {
  89778. this._pos++;
  89779. };
  89780. Tokenizer.prototype.isEnd = function () {
  89781. return this._pos >= this._maxPos;
  89782. };
  89783. return Tokenizer;
  89784. }());
  89785. /**
  89786. * Values
  89787. */
  89788. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  89789. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  89790. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  89791. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  89792. /**
  89793. * Parse
  89794. */
  89795. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  89796. for (var buf in parsedBuffers) {
  89797. var parsedBuffer = parsedBuffers[buf];
  89798. gltfRuntime.buffers[buf] = parsedBuffer;
  89799. gltfRuntime.buffersCount++;
  89800. }
  89801. };
  89802. var parseShaders = function (parsedShaders, gltfRuntime) {
  89803. for (var sha in parsedShaders) {
  89804. var parsedShader = parsedShaders[sha];
  89805. gltfRuntime.shaders[sha] = parsedShader;
  89806. gltfRuntime.shaderscount++;
  89807. }
  89808. };
  89809. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  89810. for (var object in parsedObjects) {
  89811. var parsedObject = parsedObjects[object];
  89812. gltfRuntime[runtimeProperty][object] = parsedObject;
  89813. }
  89814. };
  89815. /**
  89816. * Utils
  89817. */
  89818. var normalizeUVs = function (buffer) {
  89819. if (!buffer) {
  89820. return;
  89821. }
  89822. for (var i = 0; i < buffer.length / 2; i++) {
  89823. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  89824. }
  89825. };
  89826. var getAttribute = function (attributeParameter) {
  89827. if (attributeParameter.semantic === "NORMAL") {
  89828. return "normal";
  89829. }
  89830. else if (attributeParameter.semantic === "POSITION") {
  89831. return "position";
  89832. }
  89833. else if (attributeParameter.semantic === "JOINT") {
  89834. return "matricesIndices";
  89835. }
  89836. else if (attributeParameter.semantic === "WEIGHT") {
  89837. return "matricesWeights";
  89838. }
  89839. else if (attributeParameter.semantic === "COLOR") {
  89840. return "color";
  89841. }
  89842. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  89843. var channel = Number(attributeParameter.semantic.split("_")[1]);
  89844. return "uv" + (channel === 0 ? "" : channel + 1);
  89845. }
  89846. return null;
  89847. };
  89848. /**
  89849. * Loads and creates animations
  89850. */
  89851. var loadAnimations = function (gltfRuntime) {
  89852. for (var anim in gltfRuntime.animations) {
  89853. var animation = gltfRuntime.animations[anim];
  89854. if (!animation.channels || !animation.samplers) {
  89855. continue;
  89856. }
  89857. var lastAnimation = null;
  89858. for (var i = 0; i < animation.channels.length; i++) {
  89859. // Get parameters and load buffers
  89860. var channel = animation.channels[i];
  89861. var sampler = animation.samplers[channel.sampler];
  89862. if (!sampler) {
  89863. continue;
  89864. }
  89865. var inputData = null;
  89866. var outputData = null;
  89867. if (animation.parameters) {
  89868. inputData = animation.parameters[sampler.input];
  89869. outputData = animation.parameters[sampler.output];
  89870. }
  89871. else {
  89872. inputData = sampler.input;
  89873. outputData = sampler.output;
  89874. }
  89875. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  89876. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  89877. var targetID = channel.target.id;
  89878. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  89879. if (targetNode === null) {
  89880. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  89881. }
  89882. if (targetNode === null) {
  89883. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  89884. continue;
  89885. }
  89886. var isBone = targetNode instanceof BABYLON.Bone;
  89887. // Get target path (position, rotation or scaling)
  89888. var targetPath = channel.target.path;
  89889. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  89890. if (targetPathIndex !== -1) {
  89891. targetPath = babylonAnimationPaths[targetPathIndex];
  89892. }
  89893. // Determine animation type
  89894. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  89895. if (!isBone) {
  89896. if (targetPath === "rotationQuaternion") {
  89897. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89898. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  89899. }
  89900. else {
  89901. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89902. }
  89903. }
  89904. // Create animation and key frames
  89905. var babylonAnimation = null;
  89906. var keys = [];
  89907. var arrayOffset = 0;
  89908. var modifyKey = false;
  89909. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  89910. babylonAnimation = lastAnimation;
  89911. modifyKey = true;
  89912. }
  89913. if (!modifyKey) {
  89914. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89915. }
  89916. // For each frame
  89917. for (var j = 0; j < bufferInput.length; j++) {
  89918. var value = null;
  89919. if (targetPath === "rotationQuaternion") {
  89920. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  89921. arrayOffset += 4;
  89922. }
  89923. else {
  89924. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  89925. arrayOffset += 3;
  89926. }
  89927. if (isBone) {
  89928. var bone = targetNode;
  89929. var translation = BABYLON.Vector3.Zero();
  89930. var rotationQuaternion = new BABYLON.Quaternion();
  89931. var scaling = BABYLON.Vector3.Zero();
  89932. // Warning on decompose
  89933. var mat = bone.getBaseMatrix();
  89934. if (modifyKey && lastAnimation) {
  89935. mat = lastAnimation.getKeys()[j].value;
  89936. }
  89937. mat.decompose(scaling, rotationQuaternion, translation);
  89938. if (targetPath === "position") {
  89939. translation = value;
  89940. }
  89941. else if (targetPath === "rotationQuaternion") {
  89942. rotationQuaternion = value;
  89943. }
  89944. else {
  89945. scaling = value;
  89946. }
  89947. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  89948. }
  89949. if (!modifyKey) {
  89950. keys.push({
  89951. frame: bufferInput[j],
  89952. value: value
  89953. });
  89954. }
  89955. else if (lastAnimation) {
  89956. lastAnimation.getKeys()[j].value = value;
  89957. }
  89958. }
  89959. // Finish
  89960. if (!modifyKey && babylonAnimation) {
  89961. babylonAnimation.setKeys(keys);
  89962. targetNode.animations.push(babylonAnimation);
  89963. }
  89964. lastAnimation = babylonAnimation;
  89965. gltfRuntime.scene.stopAnimation(targetNode);
  89966. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  89967. }
  89968. }
  89969. };
  89970. /**
  89971. * Returns the bones transformation matrix
  89972. */
  89973. var configureBoneTransformation = function (node) {
  89974. var mat = null;
  89975. if (node.translation || node.rotation || node.scale) {
  89976. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  89977. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  89978. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  89979. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  89980. }
  89981. else {
  89982. mat = BABYLON.Matrix.FromArray(node.matrix);
  89983. }
  89984. return mat;
  89985. };
  89986. /**
  89987. * Returns the parent bone
  89988. */
  89989. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  89990. // Try to find
  89991. for (var i = 0; i < newSkeleton.bones.length; i++) {
  89992. if (newSkeleton.bones[i].name === jointName) {
  89993. return newSkeleton.bones[i];
  89994. }
  89995. }
  89996. // Not found, search in gltf nodes
  89997. var nodes = gltfRuntime.nodes;
  89998. for (var nde in nodes) {
  89999. var node = nodes[nde];
  90000. if (!node.jointName) {
  90001. continue;
  90002. }
  90003. var children = node.children;
  90004. for (var i = 0; i < children.length; i++) {
  90005. var child = gltfRuntime.nodes[children[i]];
  90006. if (!child.jointName) {
  90007. continue;
  90008. }
  90009. if (child.jointName === jointName) {
  90010. var mat = configureBoneTransformation(node);
  90011. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90012. bone.id = nde;
  90013. return bone;
  90014. }
  90015. }
  90016. }
  90017. return null;
  90018. };
  90019. /**
  90020. * Returns the appropriate root node
  90021. */
  90022. var getNodeToRoot = function (nodesToRoot, id) {
  90023. for (var i = 0; i < nodesToRoot.length; i++) {
  90024. var nodeToRoot = nodesToRoot[i];
  90025. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90026. var child = nodeToRoot.node.children[j];
  90027. if (child === id) {
  90028. return nodeToRoot.bone;
  90029. }
  90030. }
  90031. }
  90032. return null;
  90033. };
  90034. /**
  90035. * Returns the node with the joint name
  90036. */
  90037. var getJointNode = function (gltfRuntime, jointName) {
  90038. var nodes = gltfRuntime.nodes;
  90039. var node = nodes[jointName];
  90040. if (node) {
  90041. return {
  90042. node: node,
  90043. id: jointName
  90044. };
  90045. }
  90046. for (var nde in nodes) {
  90047. node = nodes[nde];
  90048. if (node.jointName === jointName) {
  90049. return {
  90050. node: node,
  90051. id: nde
  90052. };
  90053. }
  90054. }
  90055. return null;
  90056. };
  90057. /**
  90058. * Checks if a nodes is in joints
  90059. */
  90060. var nodeIsInJoints = function (skins, id) {
  90061. for (var i = 0; i < skins.jointNames.length; i++) {
  90062. if (skins.jointNames[i] === id) {
  90063. return true;
  90064. }
  90065. }
  90066. return false;
  90067. };
  90068. /**
  90069. * Fills the nodes to root for bones and builds hierarchy
  90070. */
  90071. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90072. // Creates nodes for root
  90073. for (var nde in gltfRuntime.nodes) {
  90074. var node = gltfRuntime.nodes[nde];
  90075. var id = nde;
  90076. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90077. continue;
  90078. }
  90079. // Create node to root bone
  90080. var mat = configureBoneTransformation(node);
  90081. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90082. bone.id = id;
  90083. nodesToRoot.push({ bone: bone, node: node, id: id });
  90084. }
  90085. // Parenting
  90086. for (var i = 0; i < nodesToRoot.length; i++) {
  90087. var nodeToRoot = nodesToRoot[i];
  90088. var children = nodeToRoot.node.children;
  90089. for (var j = 0; j < children.length; j++) {
  90090. var child = null;
  90091. for (var k = 0; k < nodesToRoot.length; k++) {
  90092. if (nodesToRoot[k].id === children[j]) {
  90093. child = nodesToRoot[k];
  90094. break;
  90095. }
  90096. }
  90097. if (child) {
  90098. child.bone._parent = nodeToRoot.bone;
  90099. nodeToRoot.bone.children.push(child.bone);
  90100. }
  90101. }
  90102. }
  90103. };
  90104. /**
  90105. * Imports a skeleton
  90106. */
  90107. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90108. if (!newSkeleton) {
  90109. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90110. }
  90111. if (!skins.babylonSkeleton) {
  90112. return newSkeleton;
  90113. }
  90114. // Find the root bones
  90115. var nodesToRoot = [];
  90116. var nodesToRootToAdd = [];
  90117. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90118. newSkeleton.bones = [];
  90119. // Joints
  90120. for (var i = 0; i < skins.jointNames.length; i++) {
  90121. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90122. if (!jointNode) {
  90123. continue;
  90124. }
  90125. var node = jointNode.node;
  90126. if (!node) {
  90127. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90128. continue;
  90129. }
  90130. var id = jointNode.id;
  90131. // Optimize, if the bone already exists...
  90132. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90133. if (existingBone) {
  90134. newSkeleton.bones.push(existingBone);
  90135. continue;
  90136. }
  90137. // Search for parent bone
  90138. var foundBone = false;
  90139. var parentBone = null;
  90140. for (var j = 0; j < i; j++) {
  90141. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90142. if (!jointNode_1) {
  90143. continue;
  90144. }
  90145. var joint = jointNode_1.node;
  90146. if (!joint) {
  90147. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90148. continue;
  90149. }
  90150. var children = joint.children;
  90151. if (!children) {
  90152. continue;
  90153. }
  90154. foundBone = false;
  90155. for (var k = 0; k < children.length; k++) {
  90156. if (children[k] === id) {
  90157. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90158. foundBone = true;
  90159. break;
  90160. }
  90161. }
  90162. if (foundBone) {
  90163. break;
  90164. }
  90165. }
  90166. // Create bone
  90167. var mat = configureBoneTransformation(node);
  90168. if (!parentBone && nodesToRoot.length > 0) {
  90169. parentBone = getNodeToRoot(nodesToRoot, id);
  90170. if (parentBone) {
  90171. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90172. nodesToRootToAdd.push(parentBone);
  90173. }
  90174. }
  90175. }
  90176. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90177. bone.id = id;
  90178. }
  90179. // Polish
  90180. var bones = newSkeleton.bones;
  90181. newSkeleton.bones = [];
  90182. for (var i = 0; i < skins.jointNames.length; i++) {
  90183. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90184. if (!jointNode) {
  90185. continue;
  90186. }
  90187. for (var j = 0; j < bones.length; j++) {
  90188. if (bones[j].id === jointNode.id) {
  90189. newSkeleton.bones.push(bones[j]);
  90190. break;
  90191. }
  90192. }
  90193. }
  90194. newSkeleton.prepare();
  90195. // Finish
  90196. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90197. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90198. }
  90199. return newSkeleton;
  90200. };
  90201. /**
  90202. * Imports a mesh and its geometries
  90203. */
  90204. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90205. if (!newMesh) {
  90206. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90207. newMesh.id = id;
  90208. }
  90209. if (!node.babylonNode) {
  90210. return newMesh;
  90211. }
  90212. var subMaterials = [];
  90213. var vertexData = null;
  90214. var verticesStarts = new Array();
  90215. var verticesCounts = new Array();
  90216. var indexStarts = new Array();
  90217. var indexCounts = new Array();
  90218. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90219. var meshID = meshes[meshIndex];
  90220. var mesh = gltfRuntime.meshes[meshID];
  90221. if (!mesh) {
  90222. continue;
  90223. }
  90224. // Positions, normals and UVs
  90225. for (var i = 0; i < mesh.primitives.length; i++) {
  90226. // Temporary vertex data
  90227. var tempVertexData = new BABYLON.VertexData();
  90228. var primitive = mesh.primitives[i];
  90229. if (primitive.mode !== 4) {
  90230. // continue;
  90231. }
  90232. var attributes = primitive.attributes;
  90233. var accessor = null;
  90234. var buffer = null;
  90235. // Set positions, normal and uvs
  90236. for (var semantic in attributes) {
  90237. // Link accessor and buffer view
  90238. accessor = gltfRuntime.accessors[attributes[semantic]];
  90239. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90240. if (semantic === "NORMAL") {
  90241. tempVertexData.normals = new Float32Array(buffer.length);
  90242. tempVertexData.normals.set(buffer);
  90243. }
  90244. else if (semantic === "POSITION") {
  90245. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90246. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90247. for (var j = 0; j < buffer.length; j += 4) {
  90248. tempVertexData.positions[j] = buffer[j];
  90249. tempVertexData.positions[j + 1] = buffer[j + 1];
  90250. tempVertexData.positions[j + 2] = buffer[j + 2];
  90251. }
  90252. }
  90253. else {
  90254. tempVertexData.positions = new Float32Array(buffer.length);
  90255. tempVertexData.positions.set(buffer);
  90256. }
  90257. verticesCounts.push(tempVertexData.positions.length);
  90258. }
  90259. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90260. var channel = Number(semantic.split("_")[1]);
  90261. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90262. var uvs = new Float32Array(buffer.length);
  90263. uvs.set(buffer);
  90264. normalizeUVs(uvs);
  90265. tempVertexData.set(uvs, uvKind);
  90266. }
  90267. else if (semantic === "JOINT") {
  90268. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90269. tempVertexData.matricesIndices.set(buffer);
  90270. }
  90271. else if (semantic === "WEIGHT") {
  90272. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90273. tempVertexData.matricesWeights.set(buffer);
  90274. }
  90275. else if (semantic === "COLOR") {
  90276. tempVertexData.colors = new Float32Array(buffer.length);
  90277. tempVertexData.colors.set(buffer);
  90278. }
  90279. }
  90280. // Indices
  90281. accessor = gltfRuntime.accessors[primitive.indices];
  90282. if (accessor) {
  90283. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90284. tempVertexData.indices = new Int32Array(buffer.length);
  90285. tempVertexData.indices.set(buffer);
  90286. indexCounts.push(tempVertexData.indices.length);
  90287. }
  90288. else {
  90289. // Set indices on the fly
  90290. var indices = [];
  90291. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90292. indices.push(j);
  90293. }
  90294. tempVertexData.indices = new Int32Array(indices);
  90295. indexCounts.push(tempVertexData.indices.length);
  90296. }
  90297. if (!vertexData) {
  90298. vertexData = tempVertexData;
  90299. }
  90300. else {
  90301. vertexData.merge(tempVertexData);
  90302. }
  90303. // Sub material
  90304. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90305. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90306. // Update vertices start and index start
  90307. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90308. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90309. }
  90310. }
  90311. var material;
  90312. if (subMaterials.length > 1) {
  90313. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90314. material.subMaterials = subMaterials;
  90315. }
  90316. else {
  90317. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90318. }
  90319. if (subMaterials.length === 1) {
  90320. material = subMaterials[0];
  90321. }
  90322. if (!newMesh.material) {
  90323. newMesh.material = material;
  90324. }
  90325. // Apply geometry
  90326. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90327. newMesh.computeWorldMatrix(true);
  90328. // Apply submeshes
  90329. newMesh.subMeshes = [];
  90330. var index = 0;
  90331. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90332. var meshID = meshes[meshIndex];
  90333. var mesh = gltfRuntime.meshes[meshID];
  90334. if (!mesh) {
  90335. continue;
  90336. }
  90337. for (var i = 0; i < mesh.primitives.length; i++) {
  90338. if (mesh.primitives[i].mode !== 4) {
  90339. //continue;
  90340. }
  90341. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90342. index++;
  90343. }
  90344. }
  90345. // Finish
  90346. return newMesh;
  90347. };
  90348. /**
  90349. * Configure node transformation from position, rotation and scaling
  90350. */
  90351. var configureNode = function (newNode, position, rotation, scaling) {
  90352. if (newNode.position) {
  90353. newNode.position = position;
  90354. }
  90355. if (newNode.rotationQuaternion || newNode.rotation) {
  90356. newNode.rotationQuaternion = rotation;
  90357. }
  90358. if (newNode.scaling) {
  90359. newNode.scaling = scaling;
  90360. }
  90361. };
  90362. /**
  90363. * Configures node from transformation matrix
  90364. */
  90365. var configureNodeFromMatrix = function (newNode, node, parent) {
  90366. if (node.matrix) {
  90367. var position = new BABYLON.Vector3(0, 0, 0);
  90368. var rotation = new BABYLON.Quaternion();
  90369. var scaling = new BABYLON.Vector3(0, 0, 0);
  90370. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90371. mat.decompose(scaling, rotation, position);
  90372. configureNode(newNode, position, rotation, scaling);
  90373. }
  90374. else if (node.translation && node.rotation && node.scale) {
  90375. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90376. }
  90377. newNode.computeWorldMatrix(true);
  90378. };
  90379. /**
  90380. * Imports a node
  90381. */
  90382. var importNode = function (gltfRuntime, node, id, parent) {
  90383. var lastNode = null;
  90384. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90385. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90386. return null;
  90387. }
  90388. }
  90389. // Meshes
  90390. if (node.skin) {
  90391. if (node.meshes) {
  90392. var skin = gltfRuntime.skins[node.skin];
  90393. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90394. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90395. if (newMesh.skeleton === null) {
  90396. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90397. if (!skin.babylonSkeleton) {
  90398. skin.babylonSkeleton = newMesh.skeleton;
  90399. }
  90400. }
  90401. lastNode = newMesh;
  90402. }
  90403. }
  90404. else if (node.meshes) {
  90405. /**
  90406. * Improve meshes property
  90407. */
  90408. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90409. lastNode = newMesh;
  90410. }
  90411. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90412. var light = gltfRuntime.lights[node.light];
  90413. if (light) {
  90414. if (light.type === "ambient") {
  90415. var ambienLight = light[light.type];
  90416. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90417. hemiLight.name = node.name || "";
  90418. if (ambienLight.color) {
  90419. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  90420. }
  90421. lastNode = hemiLight;
  90422. }
  90423. else if (light.type === "directional") {
  90424. var directionalLight = light[light.type];
  90425. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90426. dirLight.name = node.name || "";
  90427. if (directionalLight.color) {
  90428. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  90429. }
  90430. lastNode = dirLight;
  90431. }
  90432. else if (light.type === "point") {
  90433. var pointLight = light[light.type];
  90434. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90435. ptLight.name = node.name || "";
  90436. if (pointLight.color) {
  90437. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  90438. }
  90439. lastNode = ptLight;
  90440. }
  90441. else if (light.type === "spot") {
  90442. var spotLight = light[light.type];
  90443. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  90444. spLight.name = node.name || "";
  90445. if (spotLight.color) {
  90446. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  90447. }
  90448. if (spotLight.fallOfAngle) {
  90449. spLight.angle = spotLight.fallOfAngle;
  90450. }
  90451. if (spotLight.fallOffExponent) {
  90452. spLight.exponent = spotLight.fallOffExponent;
  90453. }
  90454. lastNode = spLight;
  90455. }
  90456. }
  90457. }
  90458. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90459. var camera = gltfRuntime.cameras[node.camera];
  90460. if (camera) {
  90461. if (camera.type === "orthographic") {
  90462. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90463. orthoCamera.name = node.name || "";
  90464. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  90465. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90466. lastNode = orthoCamera;
  90467. }
  90468. else if (camera.type === "perspective") {
  90469. var perspectiveCamera = camera[camera.type];
  90470. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90471. persCamera.name = node.name || "";
  90472. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90473. if (!perspectiveCamera.aspectRatio) {
  90474. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  90475. }
  90476. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  90477. persCamera.maxZ = perspectiveCamera.zfar;
  90478. persCamera.minZ = perspectiveCamera.znear;
  90479. }
  90480. lastNode = persCamera;
  90481. }
  90482. }
  90483. }
  90484. // Empty node
  90485. if (!node.jointName) {
  90486. if (node.babylonNode) {
  90487. return node.babylonNode;
  90488. }
  90489. else if (lastNode === null) {
  90490. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90491. node.babylonNode = dummy;
  90492. lastNode = dummy;
  90493. }
  90494. }
  90495. if (lastNode !== null) {
  90496. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  90497. configureNodeFromMatrix(lastNode, node, parent);
  90498. }
  90499. else {
  90500. var translation = node.translation || [0, 0, 0];
  90501. var rotation = node.rotation || [0, 0, 0, 1];
  90502. var scale = node.scale || [1, 1, 1];
  90503. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  90504. }
  90505. lastNode.updateCache(true);
  90506. node.babylonNode = lastNode;
  90507. }
  90508. return lastNode;
  90509. };
  90510. /**
  90511. * Traverses nodes and creates them
  90512. */
  90513. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  90514. if (meshIncluded === void 0) { meshIncluded = false; }
  90515. var node = gltfRuntime.nodes[id];
  90516. var newNode = null;
  90517. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  90518. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  90519. meshIncluded = true;
  90520. }
  90521. else {
  90522. meshIncluded = false;
  90523. }
  90524. }
  90525. else {
  90526. meshIncluded = true;
  90527. }
  90528. if (!node.jointName && meshIncluded) {
  90529. newNode = importNode(gltfRuntime, node, id, parent);
  90530. if (newNode !== null) {
  90531. newNode.id = id;
  90532. newNode.parent = parent;
  90533. }
  90534. }
  90535. if (node.children) {
  90536. for (var i = 0; i < node.children.length; i++) {
  90537. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  90538. }
  90539. }
  90540. };
  90541. /**
  90542. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  90543. */
  90544. var postLoad = function (gltfRuntime) {
  90545. // Nodes
  90546. var currentScene = gltfRuntime.currentScene;
  90547. if (currentScene) {
  90548. for (var i = 0; i < currentScene.nodes.length; i++) {
  90549. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90550. }
  90551. }
  90552. else {
  90553. for (var thing in gltfRuntime.scenes) {
  90554. currentScene = gltfRuntime.scenes[thing];
  90555. for (var i = 0; i < currentScene.nodes.length; i++) {
  90556. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90557. }
  90558. }
  90559. }
  90560. // Set animations
  90561. loadAnimations(gltfRuntime);
  90562. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  90563. var skeleton = gltfRuntime.scene.skeletons[i];
  90564. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  90565. }
  90566. };
  90567. /**
  90568. * onBind shaderrs callback to set uniforms and matrices
  90569. */
  90570. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  90571. var materialValues = material.values || technique.parameters;
  90572. for (var unif in unTreatedUniforms) {
  90573. var uniform = unTreatedUniforms[unif];
  90574. var type = uniform.type;
  90575. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  90576. if (uniform.semantic && !uniform.source && !uniform.node) {
  90577. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  90578. }
  90579. else if (uniform.semantic && (uniform.source || uniform.node)) {
  90580. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  90581. if (source === null) {
  90582. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  90583. }
  90584. if (source === null) {
  90585. continue;
  90586. }
  90587. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  90588. }
  90589. }
  90590. else {
  90591. var value = materialValues[technique.uniforms[unif]];
  90592. if (!value) {
  90593. continue;
  90594. }
  90595. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90596. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  90597. if (texture === null || texture === undefined) {
  90598. continue;
  90599. }
  90600. shaderMaterial.getEffect().setTexture(unif, texture);
  90601. }
  90602. else {
  90603. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  90604. }
  90605. }
  90606. }
  90607. onSuccess(shaderMaterial);
  90608. };
  90609. /**
  90610. * Prepare uniforms to send the only one time
  90611. * Loads the appropriate textures
  90612. */
  90613. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  90614. var materialValues = material.values || technique.parameters;
  90615. var techniqueUniforms = technique.uniforms;
  90616. /**
  90617. * Prepare values here (not matrices)
  90618. */
  90619. for (var unif in unTreatedUniforms) {
  90620. var uniform = unTreatedUniforms[unif];
  90621. var type = uniform.type;
  90622. var value = materialValues[techniqueUniforms[unif]];
  90623. if (value === undefined) {
  90624. // In case the value is the same for all materials
  90625. value = uniform.value;
  90626. }
  90627. if (!value) {
  90628. continue;
  90629. }
  90630. var onLoadTexture = function (uniformName) {
  90631. return function (texture) {
  90632. if (uniform.value && uniformName) {
  90633. // Static uniform
  90634. shaderMaterial.setTexture(uniformName, texture);
  90635. delete unTreatedUniforms[uniformName];
  90636. }
  90637. };
  90638. };
  90639. // Texture (sampler2D)
  90640. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90641. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  90642. }
  90643. else {
  90644. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  90645. // Static uniform
  90646. delete unTreatedUniforms[unif];
  90647. }
  90648. }
  90649. }
  90650. };
  90651. /**
  90652. * Shader compilation failed
  90653. */
  90654. var onShaderCompileError = function (program, shaderMaterial, onError) {
  90655. return function (effect, error) {
  90656. shaderMaterial.dispose(true);
  90657. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  90658. };
  90659. };
  90660. /**
  90661. * Shader compilation success
  90662. */
  90663. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  90664. return function (_) {
  90665. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  90666. shaderMaterial.onBind = function (mesh) {
  90667. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  90668. };
  90669. };
  90670. };
  90671. /**
  90672. * Returns the appropriate uniform if already handled by babylon
  90673. */
  90674. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  90675. for (var unif in technique.uniforms) {
  90676. var uniform = technique.uniforms[unif];
  90677. var uniformParameter = technique.parameters[uniform];
  90678. if (tokenizer.currentIdentifier === unif) {
  90679. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  90680. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90681. if (transformIndex !== -1) {
  90682. delete unTreatedUniforms[unif];
  90683. return babylonTransforms[transformIndex];
  90684. }
  90685. }
  90686. }
  90687. }
  90688. return tokenizer.currentIdentifier;
  90689. };
  90690. /**
  90691. * All shaders loaded. Create materials one by one
  90692. */
  90693. var importMaterials = function (gltfRuntime) {
  90694. // Create materials
  90695. for (var mat in gltfRuntime.materials) {
  90696. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  90697. }
  90698. };
  90699. /**
  90700. * Implementation of the base glTF spec
  90701. */
  90702. var GLTFLoaderBase = /** @class */ (function () {
  90703. function GLTFLoaderBase() {
  90704. }
  90705. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  90706. var gltfRuntime = {
  90707. extensions: {},
  90708. accessors: {},
  90709. buffers: {},
  90710. bufferViews: {},
  90711. meshes: {},
  90712. lights: {},
  90713. cameras: {},
  90714. nodes: {},
  90715. images: {},
  90716. textures: {},
  90717. shaders: {},
  90718. programs: {},
  90719. samplers: {},
  90720. techniques: {},
  90721. materials: {},
  90722. animations: {},
  90723. skins: {},
  90724. extensionsUsed: [],
  90725. scenes: {},
  90726. buffersCount: 0,
  90727. shaderscount: 0,
  90728. scene: scene,
  90729. rootUrl: rootUrl,
  90730. loadedBufferCount: 0,
  90731. loadedBufferViews: {},
  90732. loadedShaderCount: 0,
  90733. importOnlyMeshes: false,
  90734. dummyNodes: []
  90735. };
  90736. // Parse
  90737. if (parsedData.extensions) {
  90738. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  90739. }
  90740. if (parsedData.extensionsUsed) {
  90741. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  90742. }
  90743. if (parsedData.buffers) {
  90744. parseBuffers(parsedData.buffers, gltfRuntime);
  90745. }
  90746. if (parsedData.bufferViews) {
  90747. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  90748. }
  90749. if (parsedData.accessors) {
  90750. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  90751. }
  90752. if (parsedData.meshes) {
  90753. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  90754. }
  90755. if (parsedData.lights) {
  90756. parseObject(parsedData.lights, "lights", gltfRuntime);
  90757. }
  90758. if (parsedData.cameras) {
  90759. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  90760. }
  90761. if (parsedData.nodes) {
  90762. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  90763. }
  90764. if (parsedData.images) {
  90765. parseObject(parsedData.images, "images", gltfRuntime);
  90766. }
  90767. if (parsedData.textures) {
  90768. parseObject(parsedData.textures, "textures", gltfRuntime);
  90769. }
  90770. if (parsedData.shaders) {
  90771. parseShaders(parsedData.shaders, gltfRuntime);
  90772. }
  90773. if (parsedData.programs) {
  90774. parseObject(parsedData.programs, "programs", gltfRuntime);
  90775. }
  90776. if (parsedData.samplers) {
  90777. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  90778. }
  90779. if (parsedData.techniques) {
  90780. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  90781. }
  90782. if (parsedData.materials) {
  90783. parseObject(parsedData.materials, "materials", gltfRuntime);
  90784. }
  90785. if (parsedData.animations) {
  90786. parseObject(parsedData.animations, "animations", gltfRuntime);
  90787. }
  90788. if (parsedData.skins) {
  90789. parseObject(parsedData.skins, "skins", gltfRuntime);
  90790. }
  90791. if (parsedData.scenes) {
  90792. gltfRuntime.scenes = parsedData.scenes;
  90793. }
  90794. if (parsedData.scene && parsedData.scenes) {
  90795. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  90796. }
  90797. return gltfRuntime;
  90798. };
  90799. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90800. var buffer = gltfRuntime.buffers[id];
  90801. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  90802. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  90803. }
  90804. else {
  90805. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  90806. if (request) {
  90807. onError(request.status + " " + request.statusText);
  90808. }
  90809. });
  90810. }
  90811. };
  90812. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90813. var texture = gltfRuntime.textures[id];
  90814. if (!texture || !texture.source) {
  90815. onError("");
  90816. return;
  90817. }
  90818. if (texture.babylonTexture) {
  90819. onSuccess(null);
  90820. return;
  90821. }
  90822. var source = gltfRuntime.images[texture.source];
  90823. if (BABYLON.Tools.IsBase64(source.uri)) {
  90824. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  90825. }
  90826. else {
  90827. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  90828. if (request) {
  90829. onError(request.status + " " + request.statusText);
  90830. }
  90831. });
  90832. }
  90833. };
  90834. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90835. var texture = gltfRuntime.textures[id];
  90836. if (texture.babylonTexture) {
  90837. onSuccess(texture.babylonTexture);
  90838. return;
  90839. }
  90840. var sampler = gltfRuntime.samplers[texture.sampler];
  90841. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  90842. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  90843. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  90844. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  90845. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90846. var blob = new Blob([buffer]);
  90847. var blobURL = URL.createObjectURL(blob);
  90848. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  90849. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  90850. if (sampler.wrapS !== undefined) {
  90851. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  90852. }
  90853. if (sampler.wrapT !== undefined) {
  90854. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  90855. }
  90856. newTexture.name = id;
  90857. texture.babylonTexture = newTexture;
  90858. onSuccess(newTexture);
  90859. };
  90860. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90861. var shader = gltfRuntime.shaders[id];
  90862. if (BABYLON.Tools.IsBase64(shader.uri)) {
  90863. var shaderString = atob(shader.uri.split(",")[1]);
  90864. onSuccess(shaderString);
  90865. }
  90866. else {
  90867. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  90868. if (request) {
  90869. onError(request.status + " " + request.statusText);
  90870. }
  90871. });
  90872. }
  90873. };
  90874. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90875. var material = gltfRuntime.materials[id];
  90876. if (!material.technique) {
  90877. if (onError) {
  90878. onError("No technique found.");
  90879. }
  90880. return;
  90881. }
  90882. var technique = gltfRuntime.techniques[material.technique];
  90883. if (!technique) {
  90884. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90885. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  90886. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90887. onSuccess(defaultMaterial);
  90888. return;
  90889. }
  90890. var program = gltfRuntime.programs[technique.program];
  90891. var states = technique.states;
  90892. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  90893. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  90894. var newVertexShader = "";
  90895. var newPixelShader = "";
  90896. var vertexTokenizer = new Tokenizer(vertexShader);
  90897. var pixelTokenizer = new Tokenizer(pixelShader);
  90898. var unTreatedUniforms = {};
  90899. var uniforms = [];
  90900. var attributes = [];
  90901. var samplers = [];
  90902. // Fill uniform, sampler2D and attributes
  90903. for (var unif in technique.uniforms) {
  90904. var uniform = technique.uniforms[unif];
  90905. var uniformParameter = technique.parameters[uniform];
  90906. unTreatedUniforms[unif] = uniformParameter;
  90907. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  90908. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90909. if (transformIndex !== -1) {
  90910. uniforms.push(babylonTransforms[transformIndex]);
  90911. delete unTreatedUniforms[unif];
  90912. }
  90913. else {
  90914. uniforms.push(unif);
  90915. }
  90916. }
  90917. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  90918. samplers.push(unif);
  90919. }
  90920. else {
  90921. uniforms.push(unif);
  90922. }
  90923. }
  90924. for (var attr in technique.attributes) {
  90925. var attribute = technique.attributes[attr];
  90926. var attributeParameter = technique.parameters[attribute];
  90927. if (attributeParameter.semantic) {
  90928. attributes.push(getAttribute(attributeParameter));
  90929. }
  90930. }
  90931. // Configure vertex shader
  90932. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  90933. var tokenType = vertexTokenizer.currentToken;
  90934. if (tokenType !== ETokenType.IDENTIFIER) {
  90935. newVertexShader += vertexTokenizer.currentString;
  90936. continue;
  90937. }
  90938. var foundAttribute = false;
  90939. for (var attr in technique.attributes) {
  90940. var attribute = technique.attributes[attr];
  90941. var attributeParameter = technique.parameters[attribute];
  90942. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  90943. newVertexShader += getAttribute(attributeParameter);
  90944. foundAttribute = true;
  90945. break;
  90946. }
  90947. }
  90948. if (foundAttribute) {
  90949. continue;
  90950. }
  90951. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  90952. }
  90953. // Configure pixel shader
  90954. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  90955. var tokenType = pixelTokenizer.currentToken;
  90956. if (tokenType !== ETokenType.IDENTIFIER) {
  90957. newPixelShader += pixelTokenizer.currentString;
  90958. continue;
  90959. }
  90960. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  90961. }
  90962. // Create shader material
  90963. var shaderPath = {
  90964. vertex: program.vertexShader + id,
  90965. fragment: program.fragmentShader + id
  90966. };
  90967. var options = {
  90968. attributes: attributes,
  90969. uniforms: uniforms,
  90970. samplers: samplers,
  90971. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  90972. };
  90973. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  90974. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  90975. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  90976. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  90977. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  90978. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90979. if (states && states.functions) {
  90980. var functions = states.functions;
  90981. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  90982. shaderMaterial.backFaceCulling = false;
  90983. }
  90984. var blendFunc = functions.blendFuncSeparate;
  90985. if (blendFunc) {
  90986. 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) {
  90987. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  90988. }
  90989. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90990. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90991. }
  90992. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90993. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  90994. }
  90995. 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) {
  90996. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  90997. }
  90998. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90999. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91000. }
  91001. 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) {
  91002. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91003. }
  91004. }
  91005. }
  91006. };
  91007. return GLTFLoaderBase;
  91008. }());
  91009. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91010. /**
  91011. * glTF V1 Loader
  91012. */
  91013. var GLTFLoader = /** @class */ (function () {
  91014. function GLTFLoader() {
  91015. // #region Stubs for IGLTFLoader interface
  91016. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91017. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91018. this.compileMaterials = false;
  91019. this.useClipPlane = false;
  91020. this.compileShadowGenerators = false;
  91021. this.onDisposeObservable = new BABYLON.Observable();
  91022. this.onMeshLoadedObservable = new BABYLON.Observable();
  91023. this.onTextureLoadedObservable = new BABYLON.Observable();
  91024. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91025. this.onCompleteObservable = new BABYLON.Observable();
  91026. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91027. this.state = null;
  91028. }
  91029. GLTFLoader.RegisterExtension = function (extension) {
  91030. if (GLTFLoader.Extensions[extension.name]) {
  91031. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91032. return;
  91033. }
  91034. GLTFLoader.Extensions[extension.name] = extension;
  91035. };
  91036. GLTFLoader.prototype.dispose = function () { };
  91037. // #endregion
  91038. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91039. var _this = this;
  91040. scene.useRightHandedSystem = true;
  91041. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91042. gltfRuntime.importOnlyMeshes = true;
  91043. if (meshesNames === "") {
  91044. gltfRuntime.importMeshesNames = [];
  91045. }
  91046. else if (typeof meshesNames === "string") {
  91047. gltfRuntime.importMeshesNames = [meshesNames];
  91048. }
  91049. else if (meshesNames && !(meshesNames instanceof Array)) {
  91050. gltfRuntime.importMeshesNames = [meshesNames];
  91051. }
  91052. else {
  91053. gltfRuntime.importMeshesNames = [];
  91054. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91055. }
  91056. // Create nodes
  91057. _this._createNodes(gltfRuntime);
  91058. var meshes = new Array();
  91059. var skeletons = new Array();
  91060. // Fill arrays of meshes and skeletons
  91061. for (var nde in gltfRuntime.nodes) {
  91062. var node = gltfRuntime.nodes[nde];
  91063. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91064. meshes.push(node.babylonNode);
  91065. }
  91066. }
  91067. for (var skl in gltfRuntime.skins) {
  91068. var skin = gltfRuntime.skins[skl];
  91069. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91070. skeletons.push(skin.babylonSkeleton);
  91071. }
  91072. }
  91073. // Load buffers, shaders, materials, etc.
  91074. _this._loadBuffersAsync(gltfRuntime, function () {
  91075. _this._loadShadersAsync(gltfRuntime, function () {
  91076. importMaterials(gltfRuntime);
  91077. postLoad(gltfRuntime);
  91078. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91079. onSuccess(meshes, [], skeletons);
  91080. }
  91081. });
  91082. }, onProgress);
  91083. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91084. onSuccess(meshes, [], skeletons);
  91085. }
  91086. }, onError);
  91087. return true;
  91088. };
  91089. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91090. var _this = this;
  91091. return new Promise(function (resolve, reject) {
  91092. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91093. resolve({
  91094. meshes: meshes,
  91095. particleSystems: particleSystems,
  91096. skeletons: skeletons
  91097. });
  91098. }, onProgress, function (message) {
  91099. reject(new Error(message));
  91100. });
  91101. });
  91102. };
  91103. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91104. var _this = this;
  91105. scene.useRightHandedSystem = true;
  91106. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91107. // Load runtime extensios
  91108. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91109. // Create nodes
  91110. _this._createNodes(gltfRuntime);
  91111. // Load buffers, shaders, materials, etc.
  91112. _this._loadBuffersAsync(gltfRuntime, function () {
  91113. _this._loadShadersAsync(gltfRuntime, function () {
  91114. importMaterials(gltfRuntime);
  91115. postLoad(gltfRuntime);
  91116. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91117. onSuccess();
  91118. }
  91119. });
  91120. });
  91121. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91122. onSuccess();
  91123. }
  91124. }, onError);
  91125. }, onError);
  91126. };
  91127. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91128. var _this = this;
  91129. return new Promise(function (resolve, reject) {
  91130. _this._loadAsync(scene, data, rootUrl, function () {
  91131. resolve();
  91132. }, onProgress, function (message) {
  91133. reject(new Error(message));
  91134. });
  91135. });
  91136. };
  91137. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91138. var hasShaders = false;
  91139. var processShader = function (sha, shader) {
  91140. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91141. gltfRuntime.loadedShaderCount++;
  91142. if (shaderString) {
  91143. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91144. }
  91145. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91146. onload();
  91147. }
  91148. }, function () {
  91149. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91150. });
  91151. };
  91152. for (var sha in gltfRuntime.shaders) {
  91153. hasShaders = true;
  91154. var shader = gltfRuntime.shaders[sha];
  91155. if (shader) {
  91156. processShader.bind(this, sha, shader)();
  91157. }
  91158. else {
  91159. BABYLON.Tools.Error("No shader named: " + sha);
  91160. }
  91161. }
  91162. if (!hasShaders) {
  91163. onload();
  91164. }
  91165. };
  91166. ;
  91167. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91168. var hasBuffers = false;
  91169. var processBuffer = function (buf, buffer) {
  91170. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91171. gltfRuntime.loadedBufferCount++;
  91172. if (bufferView) {
  91173. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91174. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91175. }
  91176. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91177. }
  91178. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91179. onLoad();
  91180. }
  91181. }, function () {
  91182. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91183. });
  91184. };
  91185. for (var buf in gltfRuntime.buffers) {
  91186. hasBuffers = true;
  91187. var buffer = gltfRuntime.buffers[buf];
  91188. if (buffer) {
  91189. processBuffer.bind(this, buf, buffer)();
  91190. }
  91191. else {
  91192. BABYLON.Tools.Error("No buffer named: " + buf);
  91193. }
  91194. }
  91195. if (!hasBuffers) {
  91196. onLoad();
  91197. }
  91198. };
  91199. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91200. var currentScene = gltfRuntime.currentScene;
  91201. if (currentScene) {
  91202. // Only one scene even if multiple scenes are defined
  91203. for (var i = 0; i < currentScene.nodes.length; i++) {
  91204. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91205. }
  91206. }
  91207. else {
  91208. // Load all scenes
  91209. for (var thing in gltfRuntime.scenes) {
  91210. currentScene = gltfRuntime.scenes[thing];
  91211. for (var i = 0; i < currentScene.nodes.length; i++) {
  91212. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91213. }
  91214. }
  91215. }
  91216. };
  91217. GLTFLoader.Extensions = {};
  91218. return GLTFLoader;
  91219. }());
  91220. GLTF1.GLTFLoader = GLTFLoader;
  91221. ;
  91222. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91223. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91224. })(BABYLON || (BABYLON = {}));
  91225. //# sourceMappingURL=babylon.glTFLoader.js.map
  91226. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91227. var BABYLON;
  91228. (function (BABYLON) {
  91229. var GLTF1;
  91230. (function (GLTF1) {
  91231. /**
  91232. * Utils functions for GLTF
  91233. */
  91234. var GLTFUtils = /** @class */ (function () {
  91235. function GLTFUtils() {
  91236. }
  91237. /**
  91238. * Sets the given "parameter" matrix
  91239. * @param scene: the {BABYLON.Scene} object
  91240. * @param source: the source node where to pick the matrix
  91241. * @param parameter: the GLTF technique parameter
  91242. * @param uniformName: the name of the shader's uniform
  91243. * @param shaderMaterial: the shader material
  91244. */
  91245. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91246. var mat = null;
  91247. if (parameter.semantic === "MODEL") {
  91248. mat = source.getWorldMatrix();
  91249. }
  91250. else if (parameter.semantic === "PROJECTION") {
  91251. mat = scene.getProjectionMatrix();
  91252. }
  91253. else if (parameter.semantic === "VIEW") {
  91254. mat = scene.getViewMatrix();
  91255. }
  91256. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91257. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91258. }
  91259. else if (parameter.semantic === "MODELVIEW") {
  91260. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91261. }
  91262. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91263. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91264. }
  91265. else if (parameter.semantic === "MODELINVERSE") {
  91266. mat = source.getWorldMatrix().invert();
  91267. }
  91268. else if (parameter.semantic === "VIEWINVERSE") {
  91269. mat = scene.getViewMatrix().invert();
  91270. }
  91271. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91272. mat = scene.getProjectionMatrix().invert();
  91273. }
  91274. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91275. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91276. }
  91277. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91278. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91279. }
  91280. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91281. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91282. }
  91283. else {
  91284. debugger;
  91285. }
  91286. if (mat) {
  91287. switch (parameter.type) {
  91288. case GLTF1.EParameterType.FLOAT_MAT2:
  91289. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91290. break;
  91291. case GLTF1.EParameterType.FLOAT_MAT3:
  91292. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91293. break;
  91294. case GLTF1.EParameterType.FLOAT_MAT4:
  91295. shaderMaterial.setMatrix(uniformName, mat);
  91296. break;
  91297. default: break;
  91298. }
  91299. }
  91300. };
  91301. /**
  91302. * Sets the given "parameter" matrix
  91303. * @param shaderMaterial: the shader material
  91304. * @param uniform: the name of the shader's uniform
  91305. * @param value: the value of the uniform
  91306. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91307. */
  91308. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91309. switch (type) {
  91310. case GLTF1.EParameterType.FLOAT:
  91311. shaderMaterial.setFloat(uniform, value);
  91312. return true;
  91313. case GLTF1.EParameterType.FLOAT_VEC2:
  91314. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91315. return true;
  91316. case GLTF1.EParameterType.FLOAT_VEC3:
  91317. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91318. return true;
  91319. case GLTF1.EParameterType.FLOAT_VEC4:
  91320. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91321. return true;
  91322. default: return false;
  91323. }
  91324. };
  91325. /**
  91326. * Returns the wrap mode of the texture
  91327. * @param mode: the mode value
  91328. */
  91329. GLTFUtils.GetWrapMode = function (mode) {
  91330. switch (mode) {
  91331. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91332. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91333. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91334. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91335. }
  91336. };
  91337. /**
  91338. * Returns the byte stride giving an accessor
  91339. * @param accessor: the GLTF accessor objet
  91340. */
  91341. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91342. // Needs this function since "byteStride" isn't requiered in glTF format
  91343. var type = accessor.type;
  91344. switch (type) {
  91345. case "VEC2": return 2;
  91346. case "VEC3": return 3;
  91347. case "VEC4": return 4;
  91348. case "MAT2": return 4;
  91349. case "MAT3": return 9;
  91350. case "MAT4": return 16;
  91351. default: return 1;
  91352. }
  91353. };
  91354. /**
  91355. * Returns the texture filter mode giving a mode value
  91356. * @param mode: the filter mode value
  91357. */
  91358. GLTFUtils.GetTextureFilterMode = function (mode) {
  91359. switch (mode) {
  91360. case GLTF1.ETextureFilterType.LINEAR:
  91361. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91362. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91363. case GLTF1.ETextureFilterType.NEAREST:
  91364. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91365. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91366. }
  91367. };
  91368. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91369. var byteOffset = bufferView.byteOffset + byteOffset;
  91370. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91371. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91372. throw new Error("Buffer access is out of range");
  91373. }
  91374. var buffer = loadedBufferView.buffer;
  91375. byteOffset += loadedBufferView.byteOffset;
  91376. switch (componentType) {
  91377. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91378. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91379. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91380. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91381. default: return new Float32Array(buffer, byteOffset, byteLength);
  91382. }
  91383. };
  91384. /**
  91385. * Returns a buffer from its accessor
  91386. * @param gltfRuntime: the GLTF runtime
  91387. * @param accessor: the GLTF accessor
  91388. */
  91389. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91390. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91391. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91392. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91393. };
  91394. /**
  91395. * Decodes a buffer view into a string
  91396. * @param view: the buffer view
  91397. */
  91398. GLTFUtils.DecodeBufferToText = function (view) {
  91399. var result = "";
  91400. var length = view.byteLength;
  91401. for (var i = 0; i < length; ++i) {
  91402. result += String.fromCharCode(view[i]);
  91403. }
  91404. return result;
  91405. };
  91406. /**
  91407. * Returns the default material of gltf. Related to
  91408. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91409. * @param scene: the Babylon.js scene
  91410. */
  91411. GLTFUtils.GetDefaultMaterial = function (scene) {
  91412. if (!GLTFUtils._DefaultMaterial) {
  91413. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  91414. "precision highp float;",
  91415. "",
  91416. "uniform mat4 worldView;",
  91417. "uniform mat4 projection;",
  91418. "",
  91419. "attribute vec3 position;",
  91420. "",
  91421. "void main(void)",
  91422. "{",
  91423. " gl_Position = projection * worldView * vec4(position, 1.0);",
  91424. "}"
  91425. ].join("\n");
  91426. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  91427. "precision highp float;",
  91428. "",
  91429. "uniform vec4 u_emission;",
  91430. "",
  91431. "void main(void)",
  91432. "{",
  91433. " gl_FragColor = u_emission;",
  91434. "}"
  91435. ].join("\n");
  91436. var shaderPath = {
  91437. vertex: "GLTFDefaultMaterial",
  91438. fragment: "GLTFDefaultMaterial"
  91439. };
  91440. var options = {
  91441. attributes: ["position"],
  91442. uniforms: ["worldView", "projection", "u_emission"],
  91443. samplers: new Array(),
  91444. needAlphaBlending: false
  91445. };
  91446. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  91447. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  91448. }
  91449. return GLTFUtils._DefaultMaterial;
  91450. };
  91451. // The GLTF default material
  91452. GLTFUtils._DefaultMaterial = null;
  91453. return GLTFUtils;
  91454. }());
  91455. GLTF1.GLTFUtils = GLTFUtils;
  91456. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91457. })(BABYLON || (BABYLON = {}));
  91458. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91459. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91460. var BABYLON;
  91461. (function (BABYLON) {
  91462. var GLTF1;
  91463. (function (GLTF1) {
  91464. var GLTFLoaderExtension = /** @class */ (function () {
  91465. function GLTFLoaderExtension(name) {
  91466. this._name = name;
  91467. }
  91468. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  91469. get: function () {
  91470. return this._name;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. /**
  91476. * Defines an override for loading the runtime
  91477. * Return true to stop further extensions from loading the runtime
  91478. */
  91479. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91480. return false;
  91481. };
  91482. /**
  91483. * Defines an onverride for creating gltf runtime
  91484. * Return true to stop further extensions from creating the runtime
  91485. */
  91486. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91487. return false;
  91488. };
  91489. /**
  91490. * Defines an override for loading buffers
  91491. * Return true to stop further extensions from loading this buffer
  91492. */
  91493. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91494. return false;
  91495. };
  91496. /**
  91497. * Defines an override for loading texture buffers
  91498. * Return true to stop further extensions from loading this texture data
  91499. */
  91500. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91501. return false;
  91502. };
  91503. /**
  91504. * Defines an override for creating textures
  91505. * Return true to stop further extensions from loading this texture
  91506. */
  91507. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91508. return false;
  91509. };
  91510. /**
  91511. * Defines an override for loading shader strings
  91512. * Return true to stop further extensions from loading this shader data
  91513. */
  91514. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91515. return false;
  91516. };
  91517. /**
  91518. * Defines an override for loading materials
  91519. * Return true to stop further extensions from loading this material
  91520. */
  91521. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91522. return false;
  91523. };
  91524. // ---------
  91525. // Utilities
  91526. // ---------
  91527. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91528. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91529. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  91530. }, function () {
  91531. setTimeout(function () {
  91532. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91533. });
  91534. });
  91535. };
  91536. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91537. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91538. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  91539. }, function () {
  91540. setTimeout(function () {
  91541. onSuccess();
  91542. });
  91543. });
  91544. };
  91545. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91546. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91547. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91548. }, function () {
  91549. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91550. });
  91551. };
  91552. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  91553. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  91554. };
  91555. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91556. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91557. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91558. }, function () {
  91559. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91560. });
  91561. };
  91562. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91563. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91564. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91565. }, function () {
  91566. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91567. });
  91568. };
  91569. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91570. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91571. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91572. }, function () {
  91573. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91574. });
  91575. };
  91576. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91577. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91578. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91579. }, function () {
  91580. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91581. });
  91582. };
  91583. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  91584. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  91585. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  91586. if (func(loaderExtension)) {
  91587. return;
  91588. }
  91589. }
  91590. defaultFunc();
  91591. };
  91592. return GLTFLoaderExtension;
  91593. }());
  91594. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  91595. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91596. })(BABYLON || (BABYLON = {}));
  91597. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91598. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91599. var BABYLON;
  91600. (function (BABYLON) {
  91601. var GLTF1;
  91602. (function (GLTF1) {
  91603. var BinaryExtensionBufferName = "binary_glTF";
  91604. ;
  91605. ;
  91606. var GLTFBinaryExtension = /** @class */ (function (_super) {
  91607. __extends(GLTFBinaryExtension, _super);
  91608. function GLTFBinaryExtension() {
  91609. return _super.call(this, "KHR_binary_glTF") || this;
  91610. }
  91611. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91612. var extensionsUsed = data.json.extensionsUsed;
  91613. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  91614. return false;
  91615. }
  91616. this._bin = data.bin;
  91617. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91618. return true;
  91619. };
  91620. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91621. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  91622. return false;
  91623. }
  91624. if (id !== BinaryExtensionBufferName) {
  91625. return false;
  91626. }
  91627. onSuccess(this._bin);
  91628. return true;
  91629. };
  91630. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91631. var texture = gltfRuntime.textures[id];
  91632. var source = gltfRuntime.images[texture.source];
  91633. if (!source.extensions || !(this.name in source.extensions)) {
  91634. return false;
  91635. }
  91636. var sourceExt = source.extensions[this.name];
  91637. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  91638. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91639. onSuccess(buffer);
  91640. return true;
  91641. };
  91642. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91643. var shader = gltfRuntime.shaders[id];
  91644. if (!shader.extensions || !(this.name in shader.extensions)) {
  91645. return false;
  91646. }
  91647. var binaryExtensionShader = shader.extensions[this.name];
  91648. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  91649. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91650. setTimeout(function () {
  91651. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  91652. onSuccess(shaderString);
  91653. });
  91654. return true;
  91655. };
  91656. return GLTFBinaryExtension;
  91657. }(GLTF1.GLTFLoaderExtension));
  91658. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  91659. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  91660. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91661. })(BABYLON || (BABYLON = {}));
  91662. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  91663. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91664. var BABYLON;
  91665. (function (BABYLON) {
  91666. var GLTF1;
  91667. (function (GLTF1) {
  91668. ;
  91669. ;
  91670. ;
  91671. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  91672. __extends(GLTFMaterialsCommonExtension, _super);
  91673. function GLTFMaterialsCommonExtension() {
  91674. return _super.call(this, "KHR_materials_common") || this;
  91675. }
  91676. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91677. if (!gltfRuntime.extensions)
  91678. return false;
  91679. var extension = gltfRuntime.extensions[this.name];
  91680. if (!extension)
  91681. return false;
  91682. // Create lights
  91683. var lights = extension.lights;
  91684. if (lights) {
  91685. for (var thing in lights) {
  91686. var light = lights[thing];
  91687. switch (light.type) {
  91688. case "ambient":
  91689. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  91690. var ambient = light.ambient;
  91691. if (ambient) {
  91692. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  91693. }
  91694. break;
  91695. case "point":
  91696. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  91697. var point = light.point;
  91698. if (point) {
  91699. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  91700. }
  91701. break;
  91702. case "directional":
  91703. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  91704. var directional = light.directional;
  91705. if (directional) {
  91706. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  91707. }
  91708. break;
  91709. case "spot":
  91710. var spot = light.spot;
  91711. if (spot) {
  91712. 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);
  91713. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  91714. }
  91715. break;
  91716. default:
  91717. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  91718. break;
  91719. }
  91720. }
  91721. }
  91722. return false;
  91723. };
  91724. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91725. var material = gltfRuntime.materials[id];
  91726. if (!material || !material.extensions)
  91727. return false;
  91728. var extension = material.extensions[this.name];
  91729. if (!extension)
  91730. return false;
  91731. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91732. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91733. if (extension.technique === "CONSTANT") {
  91734. standardMaterial.disableLighting = true;
  91735. }
  91736. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  91737. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  91738. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  91739. // Ambient
  91740. if (typeof extension.values.ambient === "string") {
  91741. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  91742. }
  91743. else {
  91744. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  91745. }
  91746. // Diffuse
  91747. if (typeof extension.values.diffuse === "string") {
  91748. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  91749. }
  91750. else {
  91751. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  91752. }
  91753. // Emission
  91754. if (typeof extension.values.emission === "string") {
  91755. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  91756. }
  91757. else {
  91758. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  91759. }
  91760. // Specular
  91761. if (typeof extension.values.specular === "string") {
  91762. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  91763. }
  91764. else {
  91765. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  91766. }
  91767. return true;
  91768. };
  91769. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  91770. // Create buffer from texture url
  91771. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  91772. // Create texture from buffer
  91773. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  91774. }, onError);
  91775. };
  91776. return GLTFMaterialsCommonExtension;
  91777. }(GLTF1.GLTFLoaderExtension));
  91778. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  91779. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  91780. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91781. })(BABYLON || (BABYLON = {}));
  91782. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  91783. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91784. var BABYLON;
  91785. (function (BABYLON) {
  91786. var GLTF2;
  91787. (function (GLTF2) {
  91788. var ArrayItem = /** @class */ (function () {
  91789. function ArrayItem() {
  91790. }
  91791. ArrayItem.Assign = function (values) {
  91792. if (values) {
  91793. for (var index = 0; index < values.length; index++) {
  91794. values[index]._index = index;
  91795. }
  91796. }
  91797. };
  91798. return ArrayItem;
  91799. }());
  91800. GLTF2.ArrayItem = ArrayItem;
  91801. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91802. })(BABYLON || (BABYLON = {}));
  91803. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  91804. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91805. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  91806. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  91807. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91808. var BABYLON;
  91809. (function (BABYLON) {
  91810. var GLTF2;
  91811. (function (GLTF2) {
  91812. var GLTFLoader = /** @class */ (function () {
  91813. function GLTFLoader() {
  91814. this._completePromises = new Array();
  91815. this._disposed = false;
  91816. this._state = null;
  91817. this._extensions = {};
  91818. this._defaultSampler = {};
  91819. this._requests = new Array();
  91820. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91821. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91822. this.compileMaterials = false;
  91823. this.useClipPlane = false;
  91824. this.compileShadowGenerators = false;
  91825. this.onDisposeObservable = new BABYLON.Observable();
  91826. this.onMeshLoadedObservable = new BABYLON.Observable();
  91827. this.onTextureLoadedObservable = new BABYLON.Observable();
  91828. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91829. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91830. this.onCompleteObservable = new BABYLON.Observable();
  91831. }
  91832. GLTFLoader._Register = function (name, factory) {
  91833. if (GLTFLoader._Factories[name]) {
  91834. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  91835. return;
  91836. }
  91837. GLTFLoader._Factories[name] = factory;
  91838. // Keep the order of registration so that extensions registered first are called first.
  91839. GLTFLoader._Names.push(name);
  91840. };
  91841. Object.defineProperty(GLTFLoader.prototype, "state", {
  91842. get: function () {
  91843. return this._state;
  91844. },
  91845. enumerable: true,
  91846. configurable: true
  91847. });
  91848. GLTFLoader.prototype.dispose = function () {
  91849. if (this._disposed) {
  91850. return;
  91851. }
  91852. this._disposed = true;
  91853. this.onDisposeObservable.notifyObservers(this);
  91854. this.onDisposeObservable.clear();
  91855. this._clear();
  91856. };
  91857. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91858. var _this = this;
  91859. return Promise.resolve().then(function () {
  91860. var nodes = null;
  91861. if (meshesNames) {
  91862. var nodeMap_1 = {};
  91863. if (_this._gltf.nodes) {
  91864. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  91865. var node = _a[_i];
  91866. if (node.name) {
  91867. nodeMap_1[node.name] = node;
  91868. }
  91869. }
  91870. }
  91871. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  91872. nodes = names.map(function (name) {
  91873. var node = nodeMap_1[name];
  91874. if (!node) {
  91875. throw new Error("Failed to find node " + name);
  91876. }
  91877. return node;
  91878. });
  91879. }
  91880. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  91881. return {
  91882. meshes: _this._getMeshes(),
  91883. particleSystems: [],
  91884. skeletons: _this._getSkeletons(),
  91885. };
  91886. });
  91887. });
  91888. };
  91889. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91890. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  91891. };
  91892. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  91893. var _this = this;
  91894. return Promise.resolve().then(function () {
  91895. _this._loadExtensions();
  91896. _this._babylonScene = scene;
  91897. _this._rootUrl = rootUrl;
  91898. _this._progressCallback = onProgress;
  91899. _this._state = BABYLON.GLTFLoaderState.Loading;
  91900. _this._loadData(data);
  91901. _this._checkExtensions();
  91902. var promises = new Array();
  91903. if (nodes) {
  91904. promises.push(_this._loadNodesAsync(nodes));
  91905. }
  91906. else {
  91907. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  91908. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  91909. }
  91910. if (_this.compileMaterials) {
  91911. promises.push(_this._compileMaterialsAsync());
  91912. }
  91913. if (_this.compileShadowGenerators) {
  91914. promises.push(_this._compileShadowGeneratorsAsync());
  91915. }
  91916. return Promise.all(promises).then(function () {
  91917. _this._state = BABYLON.GLTFLoaderState.Ready;
  91918. _this._startAnimations();
  91919. BABYLON.Tools.SetImmediate(function () {
  91920. if (!_this._disposed) {
  91921. Promise.all(_this._completePromises).then(function () {
  91922. _this._state = BABYLON.GLTFLoaderState.Complete;
  91923. _this.onCompleteObservable.notifyObservers(_this);
  91924. _this.onCompleteObservable.clear();
  91925. _this._clear();
  91926. }).catch(function (error) {
  91927. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91928. _this._clear();
  91929. });
  91930. }
  91931. });
  91932. });
  91933. }).catch(function (error) {
  91934. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91935. _this._clear();
  91936. throw error;
  91937. });
  91938. };
  91939. GLTFLoader.prototype._loadExtensions = function () {
  91940. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91941. var name_1 = _a[_i];
  91942. var extension = GLTFLoader._Factories[name_1](this);
  91943. this._extensions[name_1] = extension;
  91944. this.onExtensionLoadedObservable.notifyObservers(extension);
  91945. }
  91946. this.onExtensionLoadedObservable.clear();
  91947. };
  91948. GLTFLoader.prototype._loadData = function (data) {
  91949. this._gltf = data.json;
  91950. this._setupData();
  91951. if (data.bin) {
  91952. var buffers = this._gltf.buffers;
  91953. if (buffers && buffers[0] && !buffers[0].uri) {
  91954. var binaryBuffer = buffers[0];
  91955. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  91956. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  91957. }
  91958. binaryBuffer._data = Promise.resolve(data.bin);
  91959. }
  91960. else {
  91961. BABYLON.Tools.Warn("Unexpected BIN chunk");
  91962. }
  91963. }
  91964. };
  91965. GLTFLoader.prototype._setupData = function () {
  91966. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  91967. GLTF2.ArrayItem.Assign(this._gltf.animations);
  91968. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  91969. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  91970. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  91971. GLTF2.ArrayItem.Assign(this._gltf.images);
  91972. GLTF2.ArrayItem.Assign(this._gltf.materials);
  91973. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  91974. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  91975. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  91976. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  91977. GLTF2.ArrayItem.Assign(this._gltf.skins);
  91978. GLTF2.ArrayItem.Assign(this._gltf.textures);
  91979. if (this._gltf.nodes) {
  91980. var nodeParents = {};
  91981. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  91982. var node = _a[_i];
  91983. if (node.children) {
  91984. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  91985. var index = _c[_b];
  91986. nodeParents[index] = node._index;
  91987. }
  91988. }
  91989. }
  91990. var rootNode = this._createRootNode();
  91991. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  91992. var node = _e[_d];
  91993. var parentIndex = nodeParents[node._index];
  91994. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  91995. }
  91996. }
  91997. };
  91998. GLTFLoader.prototype._checkExtensions = function () {
  91999. if (this._gltf.extensionsRequired) {
  92000. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92001. var name_2 = _a[_i];
  92002. var extension = this._extensions[name_2];
  92003. if (!extension || !extension.enabled) {
  92004. throw new Error("Require extension " + name_2 + " is not available");
  92005. }
  92006. }
  92007. }
  92008. };
  92009. GLTFLoader.prototype._createRootNode = function () {
  92010. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92011. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92012. switch (this.coordinateSystemMode) {
  92013. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92014. if (!this._babylonScene.useRightHandedSystem) {
  92015. rootNode.rotation = [0, 1, 0, 0];
  92016. rootNode.scale = [1, 1, -1];
  92017. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92018. }
  92019. break;
  92020. }
  92021. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92022. this._babylonScene.useRightHandedSystem = true;
  92023. break;
  92024. }
  92025. default: {
  92026. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92027. }
  92028. }
  92029. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92030. return rootNode;
  92031. };
  92032. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92033. var promises = new Array();
  92034. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92035. var node = nodes_1[_i];
  92036. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92037. }
  92038. promises.push(this._loadAnimationsAsync());
  92039. return Promise.all(promises).then(function () { });
  92040. };
  92041. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92042. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92043. if (promise) {
  92044. return promise;
  92045. }
  92046. var promises = new Array();
  92047. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92048. var index = _a[_i];
  92049. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92050. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92051. }
  92052. promises.push(this._loadAnimationsAsync());
  92053. return Promise.all(promises).then(function () { });
  92054. };
  92055. GLTFLoader.prototype._getMeshes = function () {
  92056. var meshes = new Array();
  92057. // Root mesh is always first.
  92058. meshes.push(this._rootBabylonMesh);
  92059. var nodes = this._gltf.nodes;
  92060. if (nodes) {
  92061. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92062. var node = nodes_2[_i];
  92063. if (node._babylonMesh) {
  92064. meshes.push(node._babylonMesh);
  92065. }
  92066. if (node._primitiveBabylonMeshes) {
  92067. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92068. var babylonMesh = _b[_a];
  92069. meshes.push(babylonMesh);
  92070. }
  92071. }
  92072. }
  92073. }
  92074. return meshes;
  92075. };
  92076. GLTFLoader.prototype._getSkeletons = function () {
  92077. var skeletons = new Array();
  92078. var skins = this._gltf.skins;
  92079. if (skins) {
  92080. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92081. var skin = skins_1[_i];
  92082. if (skin._babylonSkeleton) {
  92083. skeletons.push(skin._babylonSkeleton);
  92084. }
  92085. }
  92086. }
  92087. return skeletons;
  92088. };
  92089. GLTFLoader.prototype._startAnimations = function () {
  92090. var animations = this._gltf.animations;
  92091. if (!animations) {
  92092. return;
  92093. }
  92094. switch (this.animationStartMode) {
  92095. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92096. // do nothing
  92097. break;
  92098. }
  92099. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92100. var animation = animations[0];
  92101. animation._babylonAnimationGroup.start(true);
  92102. break;
  92103. }
  92104. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92105. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92106. var animation = animations_1[_i];
  92107. animation._babylonAnimationGroup.start(true);
  92108. }
  92109. break;
  92110. }
  92111. default: {
  92112. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92113. return;
  92114. }
  92115. }
  92116. };
  92117. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92118. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92119. if (promise) {
  92120. return promise;
  92121. }
  92122. if (node._babylonMesh) {
  92123. throw new Error(context + ": Invalid recursive node hierarchy");
  92124. }
  92125. var promises = new Array();
  92126. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92127. node._babylonMesh = babylonMesh;
  92128. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92129. node._babylonAnimationTargets.push(babylonMesh);
  92130. GLTFLoader._LoadTransform(node, babylonMesh);
  92131. if (node.mesh != undefined) {
  92132. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92133. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92134. }
  92135. if (node.children) {
  92136. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92137. var index = _a[_i];
  92138. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92139. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92140. }
  92141. }
  92142. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92143. return Promise.all(promises).then(function () { });
  92144. };
  92145. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92146. // TODO: instancing
  92147. var promises = new Array();
  92148. var primitives = mesh.primitives;
  92149. if (!primitives || primitives.length === 0) {
  92150. throw new Error(context + ": Primitives are missing");
  92151. }
  92152. GLTF2.ArrayItem.Assign(primitives);
  92153. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92154. var primitive = primitives_1[_i];
  92155. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92156. }
  92157. if (node.skin != undefined) {
  92158. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92159. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92160. }
  92161. return Promise.all(promises).then(function () {
  92162. if (node._primitiveBabylonMeshes) {
  92163. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92164. var primitiveBabylonMesh = _a[_i];
  92165. primitiveBabylonMesh._refreshBoundingInfo(true);
  92166. }
  92167. }
  92168. });
  92169. };
  92170. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92171. var _this = this;
  92172. var promises = new Array();
  92173. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92174. babylonMesh.setEnabled(false);
  92175. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92176. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92177. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92178. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92179. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92180. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92181. }));
  92182. if (primitive.material == undefined) {
  92183. babylonMesh.material = this._getDefaultMaterial();
  92184. }
  92185. else {
  92186. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92187. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  92188. }
  92189. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92190. return Promise.all(promises).then(function () {
  92191. babylonMesh.setEnabled(true);
  92192. });
  92193. };
  92194. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92195. var _this = this;
  92196. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92197. if (promise) {
  92198. return promise;
  92199. }
  92200. var attributes = primitive.attributes;
  92201. if (!attributes) {
  92202. throw new Error(context + ": Attributes are missing");
  92203. }
  92204. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92205. // TODO: handle other primitive modes
  92206. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92207. }
  92208. var promises = new Array();
  92209. var babylonVertexData = new BABYLON.VertexData();
  92210. if (primitive.indices == undefined) {
  92211. var positionAccessorIndex = attributes["POSITION"];
  92212. if (positionAccessorIndex != undefined) {
  92213. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92214. babylonVertexData.indices = new Uint32Array(accessor.count);
  92215. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92216. babylonVertexData.indices[i] = i;
  92217. }
  92218. }
  92219. }
  92220. else {
  92221. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92222. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92223. babylonVertexData.indices = data;
  92224. }));
  92225. }
  92226. var loadAttribute = function (attribute, kind) {
  92227. if (attributes[attribute] == undefined) {
  92228. return;
  92229. }
  92230. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92231. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92232. babylonMesh._delayInfo.push(kind);
  92233. }
  92234. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92235. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92236. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92237. if (attribute === "COLOR_0") {
  92238. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92239. babylonMesh.hasVertexAlpha = true;
  92240. if (accessor.type === "VEC3") {
  92241. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92242. }
  92243. }
  92244. babylonVertexData.set(attributeData, kind);
  92245. }));
  92246. };
  92247. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92248. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92249. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92250. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92251. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92252. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92253. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92254. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92255. return Promise.all(promises).then(function () {
  92256. return babylonVertexData;
  92257. });
  92258. };
  92259. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92260. if (!primitive.targets) {
  92261. return;
  92262. }
  92263. if (node._numMorphTargets == undefined) {
  92264. node._numMorphTargets = primitive.targets.length;
  92265. }
  92266. else if (primitive.targets.length !== node._numMorphTargets) {
  92267. throw new Error(context + ": Primitives do not have the same number of targets");
  92268. }
  92269. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92270. for (var index = 0; index < primitive.targets.length; index++) {
  92271. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92272. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92273. // TODO: tell the target whether it has positions, normals, tangents
  92274. }
  92275. };
  92276. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92277. if (!primitive.targets) {
  92278. return Promise.resolve();
  92279. }
  92280. var promises = new Array();
  92281. var morphTargetManager = babylonMesh.morphTargetManager;
  92282. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92283. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92284. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92285. }
  92286. return Promise.all(promises).then(function () { });
  92287. };
  92288. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92289. var _this = this;
  92290. var promises = new Array();
  92291. var loadAttribute = function (attribute, setData) {
  92292. if (attributes[attribute] == undefined) {
  92293. return;
  92294. }
  92295. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92296. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92297. setData(data);
  92298. }));
  92299. };
  92300. loadAttribute("POSITION", function (data) {
  92301. if (babylonVertexData.positions) {
  92302. for (var i = 0; i < data.length; i++) {
  92303. data[i] += babylonVertexData.positions[i];
  92304. }
  92305. babylonMorphTarget.setPositions(data);
  92306. }
  92307. });
  92308. loadAttribute("NORMAL", function (data) {
  92309. if (babylonVertexData.normals) {
  92310. for (var i = 0; i < data.length; i++) {
  92311. data[i] += babylonVertexData.normals[i];
  92312. }
  92313. babylonMorphTarget.setNormals(data);
  92314. }
  92315. });
  92316. loadAttribute("TANGENT", function (data) {
  92317. if (babylonVertexData.tangents) {
  92318. // Tangent data for morph targets is stored as xyz delta.
  92319. // The vertexData.tangent is stored as xyzw.
  92320. // So we need to skip every fourth vertexData.tangent.
  92321. for (var i = 0, j = 0; i < data.length; i++) {
  92322. data[i] += babylonVertexData.tangents[j++];
  92323. if ((i + 1) % 3 == 0) {
  92324. j++;
  92325. }
  92326. }
  92327. babylonMorphTarget.setTangents(data);
  92328. }
  92329. });
  92330. return Promise.all(promises).then(function () { });
  92331. };
  92332. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92333. if (accessor.componentType == 5126 /* FLOAT */) {
  92334. return data;
  92335. }
  92336. var factor = 1;
  92337. if (accessor.normalized) {
  92338. switch (accessor.componentType) {
  92339. case 5121 /* UNSIGNED_BYTE */: {
  92340. factor = 1 / 255;
  92341. break;
  92342. }
  92343. case 5123 /* UNSIGNED_SHORT */: {
  92344. factor = 1 / 65535;
  92345. break;
  92346. }
  92347. default: {
  92348. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92349. }
  92350. }
  92351. }
  92352. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92353. for (var i = 0; i < result.length; i++) {
  92354. result[i] = data[i] * factor;
  92355. }
  92356. return result;
  92357. };
  92358. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92359. var result = new Float32Array(data.length / 3 * 4);
  92360. var offset = 0;
  92361. for (var i = 0; i < result.length; i++) {
  92362. if ((i + 1) % 4 === 0) {
  92363. result[i] = 1;
  92364. }
  92365. else {
  92366. result[i] = data[offset++];
  92367. }
  92368. }
  92369. return result;
  92370. };
  92371. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92372. var position = BABYLON.Vector3.Zero();
  92373. var rotation = BABYLON.Quaternion.Identity();
  92374. var scaling = BABYLON.Vector3.One();
  92375. if (node.matrix) {
  92376. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92377. matrix.decompose(scaling, rotation, position);
  92378. }
  92379. else {
  92380. if (node.translation)
  92381. position = BABYLON.Vector3.FromArray(node.translation);
  92382. if (node.rotation)
  92383. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92384. if (node.scale)
  92385. scaling = BABYLON.Vector3.FromArray(node.scale);
  92386. }
  92387. babylonNode.position = position;
  92388. babylonNode.rotationQuaternion = rotation;
  92389. babylonNode.scaling = scaling;
  92390. };
  92391. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92392. var _this = this;
  92393. var assignSkeleton = function () {
  92394. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92395. var babylonMesh = _a[_i];
  92396. babylonMesh.skeleton = skin._babylonSkeleton;
  92397. }
  92398. node._babylonMesh.parent = _this._rootBabylonMesh;
  92399. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92400. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92401. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92402. };
  92403. if (skin._loaded) {
  92404. assignSkeleton();
  92405. return skin._loaded;
  92406. }
  92407. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  92408. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  92409. var skeletonId = "skeleton" + skin._index;
  92410. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  92411. skin._babylonSkeleton = babylonSkeleton;
  92412. _this._loadBones(context, skin, inverseBindMatricesData);
  92413. assignSkeleton();
  92414. }));
  92415. };
  92416. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  92417. if (skin.inverseBindMatrices == undefined) {
  92418. return Promise.resolve(null);
  92419. }
  92420. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  92421. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92422. return data;
  92423. });
  92424. };
  92425. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  92426. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  92427. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92428. node._babylonAnimationTargets.push(babylonBone);
  92429. return babylonBone;
  92430. };
  92431. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  92432. var babylonBones = {};
  92433. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  92434. var index = _a[_i];
  92435. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  92436. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  92437. }
  92438. };
  92439. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  92440. var babylonBone = babylonBones[node._index];
  92441. if (babylonBone) {
  92442. return babylonBone;
  92443. }
  92444. var boneIndex = skin.joints.indexOf(node._index);
  92445. var baseMatrix = BABYLON.Matrix.Identity();
  92446. if (inverseBindMatricesData && boneIndex !== -1) {
  92447. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  92448. baseMatrix.invertToRef(baseMatrix);
  92449. }
  92450. var babylonParentBone = null;
  92451. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  92452. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  92453. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  92454. }
  92455. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  92456. babylonBones[node._index] = babylonBone;
  92457. return babylonBone;
  92458. };
  92459. GLTFLoader.prototype._getNodeMatrix = function (node) {
  92460. return node.matrix ?
  92461. BABYLON.Matrix.FromArray(node.matrix) :
  92462. 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());
  92463. };
  92464. GLTFLoader.prototype._loadAnimationsAsync = function () {
  92465. var animations = this._gltf.animations;
  92466. if (!animations) {
  92467. return Promise.resolve();
  92468. }
  92469. var promises = new Array();
  92470. for (var index = 0; index < animations.length; index++) {
  92471. var animation = animations[index];
  92472. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  92473. }
  92474. return Promise.all(promises).then(function () { });
  92475. };
  92476. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  92477. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  92478. animation._babylonAnimationGroup = babylonAnimationGroup;
  92479. var promises = new Array();
  92480. GLTF2.ArrayItem.Assign(animation.channels);
  92481. GLTF2.ArrayItem.Assign(animation.samplers);
  92482. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  92483. var channel = _a[_i];
  92484. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  92485. }
  92486. return Promise.all(promises).then(function () {
  92487. babylonAnimationGroup.normalize();
  92488. });
  92489. };
  92490. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  92491. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  92492. if (!targetNode._babylonMesh) {
  92493. return Promise.resolve();
  92494. }
  92495. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  92496. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  92497. var targetPath;
  92498. var animationType;
  92499. switch (channel.target.path) {
  92500. case "translation" /* TRANSLATION */: {
  92501. targetPath = "position";
  92502. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92503. break;
  92504. }
  92505. case "rotation" /* ROTATION */: {
  92506. targetPath = "rotationQuaternion";
  92507. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92508. break;
  92509. }
  92510. case "scale" /* SCALE */: {
  92511. targetPath = "scaling";
  92512. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92513. break;
  92514. }
  92515. case "weights" /* WEIGHTS */: {
  92516. targetPath = "influence";
  92517. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  92518. break;
  92519. }
  92520. default: {
  92521. throw new Error(context + ": Invalid target path " + channel.target.path);
  92522. }
  92523. }
  92524. var outputBufferOffset = 0;
  92525. var getNextOutputValue;
  92526. switch (targetPath) {
  92527. case "position": {
  92528. getNextOutputValue = function () {
  92529. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92530. outputBufferOffset += 3;
  92531. return value;
  92532. };
  92533. break;
  92534. }
  92535. case "rotationQuaternion": {
  92536. getNextOutputValue = function () {
  92537. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  92538. outputBufferOffset += 4;
  92539. return value;
  92540. };
  92541. break;
  92542. }
  92543. case "scaling": {
  92544. getNextOutputValue = function () {
  92545. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92546. outputBufferOffset += 3;
  92547. return value;
  92548. };
  92549. break;
  92550. }
  92551. case "influence": {
  92552. getNextOutputValue = function () {
  92553. var value = new Array(targetNode._numMorphTargets);
  92554. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  92555. value[i] = data.output[outputBufferOffset++];
  92556. }
  92557. return value;
  92558. };
  92559. break;
  92560. }
  92561. }
  92562. var getNextKey;
  92563. switch (data.interpolation) {
  92564. case "STEP" /* STEP */: {
  92565. getNextKey = function (frameIndex) { return ({
  92566. frame: data.input[frameIndex],
  92567. value: getNextOutputValue(),
  92568. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  92569. }); };
  92570. break;
  92571. }
  92572. case "LINEAR" /* LINEAR */: {
  92573. getNextKey = function (frameIndex) { return ({
  92574. frame: data.input[frameIndex],
  92575. value: getNextOutputValue()
  92576. }); };
  92577. break;
  92578. }
  92579. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92580. getNextKey = function (frameIndex) { return ({
  92581. frame: data.input[frameIndex],
  92582. inTangent: getNextOutputValue(),
  92583. value: getNextOutputValue(),
  92584. outTangent: getNextOutputValue()
  92585. }); };
  92586. break;
  92587. }
  92588. }
  92589. var keys;
  92590. if (data.input.length === 1) {
  92591. var key = getNextKey(0);
  92592. keys = [
  92593. { frame: key.frame, value: key.value },
  92594. { frame: key.frame + 1, value: key.value }
  92595. ];
  92596. }
  92597. else {
  92598. keys = new Array(data.input.length);
  92599. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  92600. keys[frameIndex] = getNextKey(frameIndex);
  92601. }
  92602. }
  92603. if (targetPath === "influence") {
  92604. var _loop_1 = function (targetIndex) {
  92605. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92606. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92607. babylonAnimation.setKeys(keys.map(function (key) { return ({
  92608. frame: key.frame,
  92609. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  92610. value: key.value[targetIndex],
  92611. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  92612. }); }));
  92613. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92614. var babylonMesh = _a[_i];
  92615. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  92616. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  92617. }
  92618. };
  92619. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  92620. _loop_1(targetIndex);
  92621. }
  92622. }
  92623. else {
  92624. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92625. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92626. babylonAnimation.setKeys(keys);
  92627. if (targetNode._babylonAnimationTargets) {
  92628. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  92629. var target = _a[_i];
  92630. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  92631. }
  92632. }
  92633. }
  92634. });
  92635. };
  92636. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  92637. if (sampler._data) {
  92638. return sampler._data;
  92639. }
  92640. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  92641. switch (interpolation) {
  92642. case "STEP" /* STEP */:
  92643. case "LINEAR" /* LINEAR */:
  92644. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92645. break;
  92646. }
  92647. default: {
  92648. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  92649. }
  92650. }
  92651. var inputData;
  92652. var outputData;
  92653. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  92654. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  92655. sampler._data = Promise.all([
  92656. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  92657. inputData = data;
  92658. }),
  92659. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  92660. outputData = data;
  92661. })
  92662. ]).then(function () {
  92663. return {
  92664. input: inputData,
  92665. interpolation: interpolation,
  92666. output: outputData,
  92667. };
  92668. });
  92669. return sampler._data;
  92670. };
  92671. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  92672. if (buffer._data) {
  92673. return buffer._data;
  92674. }
  92675. if (!buffer.uri) {
  92676. throw new Error(context + ": Uri is missing");
  92677. }
  92678. buffer._data = this._loadUriAsync(context, buffer.uri);
  92679. return buffer._data;
  92680. };
  92681. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  92682. if (bufferView._data) {
  92683. return bufferView._data;
  92684. }
  92685. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  92686. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  92687. try {
  92688. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  92689. }
  92690. catch (e) {
  92691. throw new Error(context + ": " + e.message);
  92692. }
  92693. });
  92694. return bufferView._data;
  92695. };
  92696. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  92697. var _this = this;
  92698. if (accessor.sparse) {
  92699. throw new Error(context + ": Sparse accessors are not currently supported");
  92700. }
  92701. if (accessor._data) {
  92702. return accessor._data;
  92703. }
  92704. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  92705. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  92706. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  92707. var byteOffset = accessor.byteOffset || 0;
  92708. var byteStride = bufferView.byteStride;
  92709. if (byteStride === 0) {
  92710. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  92711. }
  92712. try {
  92713. switch (accessor.componentType) {
  92714. case 5120 /* BYTE */: {
  92715. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92716. }
  92717. case 5121 /* UNSIGNED_BYTE */: {
  92718. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92719. }
  92720. case 5122 /* SHORT */: {
  92721. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92722. }
  92723. case 5123 /* UNSIGNED_SHORT */: {
  92724. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92725. }
  92726. case 5125 /* UNSIGNED_INT */: {
  92727. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92728. }
  92729. case 5126 /* FLOAT */: {
  92730. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92731. }
  92732. default: {
  92733. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92734. }
  92735. }
  92736. }
  92737. catch (e) {
  92738. throw new Error(context + ": " + e);
  92739. }
  92740. });
  92741. return accessor._data;
  92742. };
  92743. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  92744. byteOffset += data.byteOffset;
  92745. var targetLength = count * numComponents;
  92746. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  92747. return new typedArray(data.buffer, byteOffset, targetLength);
  92748. }
  92749. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  92750. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  92751. var targetBuffer = new typedArray(targetLength);
  92752. var sourceIndex = 0;
  92753. var targetIndex = 0;
  92754. while (targetIndex < targetLength) {
  92755. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  92756. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  92757. targetIndex++;
  92758. }
  92759. sourceIndex += elementStride;
  92760. }
  92761. return targetBuffer;
  92762. };
  92763. GLTFLoader.prototype._getDefaultMaterial = function () {
  92764. var id = "__gltf_default";
  92765. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  92766. if (!babylonMaterial) {
  92767. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  92768. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  92769. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  92770. babylonMaterial.metallic = 1;
  92771. babylonMaterial.roughness = 1;
  92772. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92773. }
  92774. return babylonMaterial;
  92775. };
  92776. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  92777. var promises = new Array();
  92778. var babylonMaterial = material._babylonMaterial;
  92779. // Ensure metallic workflow
  92780. babylonMaterial.metallic = 1;
  92781. babylonMaterial.roughness = 1;
  92782. var properties = material.pbrMetallicRoughness;
  92783. if (properties) {
  92784. if (properties.baseColorFactor) {
  92785. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  92786. babylonMaterial.alpha = properties.baseColorFactor[3];
  92787. }
  92788. else {
  92789. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92790. }
  92791. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  92792. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  92793. if (properties.baseColorTexture) {
  92794. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  92795. babylonMaterial.albedoTexture = texture;
  92796. }));
  92797. }
  92798. if (properties.metallicRoughnessTexture) {
  92799. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  92800. babylonMaterial.metallicTexture = texture;
  92801. }));
  92802. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  92803. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  92804. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  92805. }
  92806. }
  92807. this._loadMaterialAlphaProperties(context, material);
  92808. return Promise.all(promises).then(function () { });
  92809. };
  92810. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92811. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  92812. if (promise) {
  92813. return promise;
  92814. }
  92815. material._babylonMeshes = material._babylonMeshes || [];
  92816. material._babylonMeshes.push(babylonMesh);
  92817. if (material._loaded) {
  92818. babylonMesh.material = material._babylonMaterial;
  92819. return material._loaded;
  92820. }
  92821. var promises = new Array();
  92822. var babylonMaterial = this._createMaterial(material);
  92823. material._babylonMaterial = babylonMaterial;
  92824. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  92825. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  92826. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92827. babylonMesh.material = babylonMaterial;
  92828. return (material._loaded = Promise.all(promises).then(function () { }));
  92829. };
  92830. GLTFLoader.prototype._createMaterial = function (material) {
  92831. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  92832. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  92833. return babylonMaterial;
  92834. };
  92835. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  92836. var promises = new Array();
  92837. var babylonMaterial = material._babylonMaterial;
  92838. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  92839. if (material.doubleSided) {
  92840. babylonMaterial.backFaceCulling = false;
  92841. babylonMaterial.twoSidedLighting = true;
  92842. }
  92843. if (material.normalTexture) {
  92844. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  92845. babylonMaterial.bumpTexture = texture;
  92846. }));
  92847. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  92848. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  92849. if (material.normalTexture.scale != undefined) {
  92850. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  92851. }
  92852. }
  92853. if (material.occlusionTexture) {
  92854. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  92855. babylonMaterial.ambientTexture = texture;
  92856. }));
  92857. babylonMaterial.useAmbientInGrayScale = true;
  92858. if (material.occlusionTexture.strength != undefined) {
  92859. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  92860. }
  92861. }
  92862. if (material.emissiveTexture) {
  92863. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  92864. babylonMaterial.emissiveTexture = texture;
  92865. }));
  92866. }
  92867. return Promise.all(promises).then(function () { });
  92868. };
  92869. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  92870. var babylonMaterial = material._babylonMaterial;
  92871. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  92872. switch (alphaMode) {
  92873. case "OPAQUE" /* OPAQUE */: {
  92874. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  92875. break;
  92876. }
  92877. case "MASK" /* MASK */: {
  92878. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  92879. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  92880. if (babylonMaterial.alpha) {
  92881. if (babylonMaterial.alpha === 0) {
  92882. babylonMaterial.alphaCutOff = 1;
  92883. }
  92884. else {
  92885. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  92886. }
  92887. babylonMaterial.alpha = 1;
  92888. }
  92889. if (babylonMaterial.albedoTexture) {
  92890. babylonMaterial.albedoTexture.hasAlpha = true;
  92891. }
  92892. break;
  92893. }
  92894. case "BLEND" /* BLEND */: {
  92895. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  92896. if (babylonMaterial.albedoTexture) {
  92897. babylonMaterial.albedoTexture.hasAlpha = true;
  92898. babylonMaterial.useAlphaFromAlbedoTexture = true;
  92899. }
  92900. break;
  92901. }
  92902. default: {
  92903. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  92904. }
  92905. }
  92906. };
  92907. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  92908. var _this = this;
  92909. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  92910. context = "#/textures/" + textureInfo.index;
  92911. var promises = new Array();
  92912. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  92913. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  92914. var deferred = new BABYLON.Deferred();
  92915. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  92916. if (!_this._disposed) {
  92917. deferred.resolve();
  92918. }
  92919. }, function (message, exception) {
  92920. if (!_this._disposed) {
  92921. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  92922. }
  92923. });
  92924. promises.push(deferred.promise);
  92925. babylonTexture.name = texture.name || "texture" + texture._index;
  92926. babylonTexture.wrapU = samplerData.wrapU;
  92927. babylonTexture.wrapV = samplerData.wrapV;
  92928. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  92929. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  92930. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  92931. babylonTexture.updateURL(objectURL);
  92932. }));
  92933. assign(babylonTexture);
  92934. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  92935. return Promise.all(promises).then(function () { });
  92936. };
  92937. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  92938. if (!sampler._data) {
  92939. sampler._data = {
  92940. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  92941. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  92942. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  92943. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  92944. };
  92945. }
  92946. ;
  92947. return sampler._data;
  92948. };
  92949. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  92950. if (image._objectURL) {
  92951. return image._objectURL;
  92952. }
  92953. var promise;
  92954. if (image.uri) {
  92955. promise = this._loadUriAsync(context, image.uri);
  92956. }
  92957. else {
  92958. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  92959. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  92960. }
  92961. image._objectURL = promise.then(function (data) {
  92962. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  92963. });
  92964. return image._objectURL;
  92965. };
  92966. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  92967. var _this = this;
  92968. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  92969. if (promise) {
  92970. return promise;
  92971. }
  92972. if (!GLTFLoader._ValidateUri(uri)) {
  92973. throw new Error(context + ": Uri '" + uri + "' is invalid");
  92974. }
  92975. if (BABYLON.Tools.IsBase64(uri)) {
  92976. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  92977. }
  92978. return new Promise(function (resolve, reject) {
  92979. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  92980. if (!_this._disposed) {
  92981. resolve(new Uint8Array(data));
  92982. }
  92983. }, function (event) {
  92984. if (!_this._disposed) {
  92985. try {
  92986. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  92987. request._lengthComputable = event.lengthComputable;
  92988. request._loaded = event.loaded;
  92989. request._total = event.total;
  92990. _this._onProgress();
  92991. }
  92992. }
  92993. catch (e) {
  92994. reject(e);
  92995. }
  92996. }
  92997. }, _this._babylonScene.database, true, function (request, exception) {
  92998. if (!_this._disposed) {
  92999. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93000. }
  93001. });
  93002. _this._requests.push(request);
  93003. });
  93004. };
  93005. GLTFLoader.prototype._onProgress = function () {
  93006. if (!this._progressCallback) {
  93007. return;
  93008. }
  93009. var lengthComputable = true;
  93010. var loaded = 0;
  93011. var total = 0;
  93012. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93013. var request = _a[_i];
  93014. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93015. return;
  93016. }
  93017. lengthComputable = lengthComputable && request._lengthComputable;
  93018. loaded += request._loaded;
  93019. total += request._total;
  93020. }
  93021. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93022. };
  93023. GLTFLoader._GetProperty = function (context, array, index) {
  93024. if (!array || index == undefined || !array[index]) {
  93025. throw new Error(context + ": Failed to find index " + index);
  93026. }
  93027. return array[index];
  93028. };
  93029. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93030. // Set defaults if undefined
  93031. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93032. switch (mode) {
  93033. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93034. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93035. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93036. default:
  93037. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93038. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93039. }
  93040. };
  93041. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93042. // Set defaults if undefined
  93043. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93044. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93045. if (magFilter === 9729 /* LINEAR */) {
  93046. switch (minFilter) {
  93047. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93048. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93049. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93050. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93051. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93052. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93053. default:
  93054. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93055. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93056. }
  93057. }
  93058. else {
  93059. if (magFilter !== 9728 /* NEAREST */) {
  93060. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93061. }
  93062. switch (minFilter) {
  93063. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93064. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93065. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93066. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93067. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93068. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93069. default:
  93070. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93071. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93072. }
  93073. }
  93074. };
  93075. GLTFLoader._GetNumComponents = function (context, type) {
  93076. switch (type) {
  93077. case "SCALAR": return 1;
  93078. case "VEC2": return 2;
  93079. case "VEC3": return 3;
  93080. case "VEC4": return 4;
  93081. case "MAT2": return 4;
  93082. case "MAT3": return 9;
  93083. case "MAT4": return 16;
  93084. }
  93085. throw new Error(context + ": Invalid type " + type);
  93086. };
  93087. GLTFLoader._ValidateUri = function (uri) {
  93088. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93089. };
  93090. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93091. var promises = new Array();
  93092. if (this._gltf.materials) {
  93093. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93094. var material = _a[_i];
  93095. var babylonMaterial = material._babylonMaterial;
  93096. var babylonMeshes = material._babylonMeshes;
  93097. if (babylonMaterial && babylonMeshes) {
  93098. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93099. var babylonMesh = babylonMeshes_1[_b];
  93100. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93101. if (this.useClipPlane) {
  93102. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93103. }
  93104. }
  93105. }
  93106. }
  93107. }
  93108. return Promise.all(promises).then(function () { });
  93109. };
  93110. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93111. var promises = new Array();
  93112. var lights = this._babylonScene.lights;
  93113. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93114. var light = lights_1[_i];
  93115. var generator = light.getShadowGenerator();
  93116. if (generator) {
  93117. promises.push(generator.forceCompilationAsync());
  93118. }
  93119. }
  93120. return Promise.all(promises).then(function () { });
  93121. };
  93122. GLTFLoader.prototype._clear = function () {
  93123. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93124. var request = _a[_i];
  93125. request.abort();
  93126. }
  93127. this._requests.length = 0;
  93128. if (this._gltf && this._gltf.images) {
  93129. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93130. var image = _c[_b];
  93131. if (image._objectURL) {
  93132. image._objectURL.then(function (value) {
  93133. URL.revokeObjectURL(value);
  93134. });
  93135. image._objectURL = undefined;
  93136. }
  93137. }
  93138. }
  93139. delete this._gltf;
  93140. delete this._babylonScene;
  93141. this._completePromises.length = 0;
  93142. for (var name_3 in this._extensions) {
  93143. this._extensions[name_3].dispose();
  93144. }
  93145. this._extensions = {};
  93146. delete this._rootBabylonMesh;
  93147. delete this._progressCallback;
  93148. this.onMeshLoadedObservable.clear();
  93149. this.onTextureLoadedObservable.clear();
  93150. this.onMaterialLoadedObservable.clear();
  93151. };
  93152. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93153. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93154. var name_4 = _a[_i];
  93155. var extension = this._extensions[name_4];
  93156. if (extension.enabled) {
  93157. var promise = actionAsync(extension);
  93158. if (promise) {
  93159. return promise;
  93160. }
  93161. }
  93162. }
  93163. return null;
  93164. };
  93165. GLTFLoader._Names = new Array();
  93166. GLTFLoader._Factories = {};
  93167. return GLTFLoader;
  93168. }());
  93169. GLTF2.GLTFLoader = GLTFLoader;
  93170. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93171. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93172. })(BABYLON || (BABYLON = {}));
  93173. //# sourceMappingURL=babylon.glTFLoader.js.map
  93174. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93175. var BABYLON;
  93176. (function (BABYLON) {
  93177. var GLTF2;
  93178. (function (GLTF2) {
  93179. var GLTFLoaderExtension = /** @class */ (function () {
  93180. function GLTFLoaderExtension(loader) {
  93181. this.enabled = true;
  93182. this._loader = loader;
  93183. }
  93184. GLTFLoaderExtension.prototype.dispose = function () {
  93185. delete this._loader;
  93186. };
  93187. // #region Overridable Methods
  93188. /** Override this method to modify the default behavior for loading scenes. */
  93189. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93190. /** Override this method to modify the default behavior for loading nodes. */
  93191. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93192. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93193. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93194. /** Override this method to modify the default behavior for loading materials. */
  93195. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  93196. /** Override this method to modify the default behavior for loading uris. */
  93197. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93198. // #endregion
  93199. /** Helper method called by a loader extension to load an glTF extension. */
  93200. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93201. if (!property.extensions) {
  93202. return null;
  93203. }
  93204. var extensions = property.extensions;
  93205. var extension = extensions[this.name];
  93206. if (!extension) {
  93207. return null;
  93208. }
  93209. // Clear out the extension before executing the action to avoid recursing into the same property.
  93210. delete extensions[this.name];
  93211. try {
  93212. return actionAsync(context + "/extensions/" + this.name, extension);
  93213. }
  93214. finally {
  93215. // Restore the extension after executing the action.
  93216. extensions[this.name] = extension;
  93217. }
  93218. };
  93219. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93220. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93221. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93222. };
  93223. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93224. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93225. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93226. };
  93227. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93228. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93229. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93230. };
  93231. /** Helper method called by the loader to allow extensions to override loading materials. */
  93232. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  93233. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  93234. };
  93235. /** Helper method called by the loader to allow extensions to override loading uris. */
  93236. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93237. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93238. };
  93239. return GLTFLoaderExtension;
  93240. }());
  93241. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93242. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93243. })(BABYLON || (BABYLON = {}));
  93244. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93245. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93246. var BABYLON;
  93247. (function (BABYLON) {
  93248. var GLTF2;
  93249. (function (GLTF2) {
  93250. var Extensions;
  93251. (function (Extensions) {
  93252. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93253. var NAME = "MSFT_lod";
  93254. var MSFT_lod = /** @class */ (function (_super) {
  93255. __extends(MSFT_lod, _super);
  93256. function MSFT_lod() {
  93257. var _this = _super !== null && _super.apply(this, arguments) || this;
  93258. _this.name = NAME;
  93259. /**
  93260. * Maximum number of LODs to load, starting from the lowest LOD.
  93261. */
  93262. _this.maxLODsToLoad = Number.MAX_VALUE;
  93263. _this._loadingNodeLOD = null;
  93264. _this._loadNodeSignals = {};
  93265. _this._loadingMaterialLOD = null;
  93266. _this._loadMaterialSignals = {};
  93267. return _this;
  93268. }
  93269. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93270. var _this = this;
  93271. return this._loadExtensionAsync(context, node, function (context, extension) {
  93272. var firstPromise;
  93273. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93274. var _loop_1 = function (indexLOD) {
  93275. var nodeLOD = nodeLODs[indexLOD];
  93276. if (indexLOD !== 0) {
  93277. _this._loadingNodeLOD = nodeLOD;
  93278. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93279. }
  93280. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93281. if (indexLOD !== 0) {
  93282. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93283. previousNodeLOD._babylonMesh.setEnabled(false);
  93284. }
  93285. if (indexLOD !== nodeLODs.length - 1) {
  93286. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93287. _this._loadNodeSignals[nodeIndex].resolve();
  93288. delete _this._loadNodeSignals[nodeIndex];
  93289. }
  93290. });
  93291. if (indexLOD === 0) {
  93292. firstPromise = promise;
  93293. }
  93294. else {
  93295. _this._loader._completePromises.push(promise);
  93296. _this._loadingNodeLOD = null;
  93297. }
  93298. };
  93299. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93300. _loop_1(indexLOD);
  93301. }
  93302. return firstPromise;
  93303. });
  93304. };
  93305. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93306. var _this = this;
  93307. // Don't load material LODs if already loading a node LOD.
  93308. if (this._loadingNodeLOD) {
  93309. return null;
  93310. }
  93311. return this._loadExtensionAsync(context, material, function (context, extension) {
  93312. var firstPromise;
  93313. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93314. var _loop_2 = function (indexLOD) {
  93315. var materialLOD = materialLODs[indexLOD];
  93316. if (indexLOD !== 0) {
  93317. _this._loadingMaterialLOD = materialLOD;
  93318. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93319. }
  93320. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  93321. if (indexLOD !== materialLODs.length - 1) {
  93322. var materialIndex = materialLODs[indexLOD + 1]._index;
  93323. _this._loadMaterialSignals[materialIndex].resolve();
  93324. delete _this._loadMaterialSignals[materialIndex];
  93325. }
  93326. });
  93327. if (indexLOD === 0) {
  93328. firstPromise = promise;
  93329. }
  93330. else {
  93331. _this._loader._completePromises.push(promise);
  93332. _this._loadingMaterialLOD = null;
  93333. }
  93334. };
  93335. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93336. _loop_2(indexLOD);
  93337. }
  93338. return firstPromise;
  93339. });
  93340. };
  93341. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93342. var _this = this;
  93343. // Defer the loading of uris if loading a material or node LOD.
  93344. if (this._loadingMaterialLOD) {
  93345. var index = this._loadingMaterialLOD._index;
  93346. return this._loadMaterialSignals[index].promise.then(function () {
  93347. return _this._loader._loadUriAsync(context, uri);
  93348. });
  93349. }
  93350. else if (this._loadingNodeLOD) {
  93351. var index = this._loadingNodeLOD._index;
  93352. return this._loadNodeSignals[index].promise.then(function () {
  93353. return _this._loader._loadUriAsync(context, uri);
  93354. });
  93355. }
  93356. return null;
  93357. };
  93358. /**
  93359. * Gets an array of LOD properties from lowest to highest.
  93360. */
  93361. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93362. if (this.maxLODsToLoad <= 0) {
  93363. throw new Error("maxLODsToLoad must be greater than zero");
  93364. }
  93365. var properties = new Array();
  93366. for (var i = ids.length - 1; i >= 0; i--) {
  93367. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93368. if (properties.length === this.maxLODsToLoad) {
  93369. return properties;
  93370. }
  93371. }
  93372. properties.push(property);
  93373. return properties;
  93374. };
  93375. return MSFT_lod;
  93376. }(GLTF2.GLTFLoaderExtension));
  93377. Extensions.MSFT_lod = MSFT_lod;
  93378. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93379. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93381. })(BABYLON || (BABYLON = {}));
  93382. //# sourceMappingURL=MSFT_lod.js.map
  93383. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93384. var BABYLON;
  93385. (function (BABYLON) {
  93386. var GLTF2;
  93387. (function (GLTF2) {
  93388. var Extensions;
  93389. (function (Extensions) {
  93390. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93391. var NAME = "KHR_draco_mesh_compression";
  93392. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93393. __extends(KHR_draco_mesh_compression, _super);
  93394. function KHR_draco_mesh_compression(loader) {
  93395. var _this = _super.call(this, loader) || this;
  93396. _this.name = NAME;
  93397. _this._dracoCompression = null;
  93398. // Disable extension if decoder is not available.
  93399. if (!BABYLON.DracoCompression.DecoderUrl) {
  93400. _this.enabled = false;
  93401. }
  93402. return _this;
  93403. }
  93404. KHR_draco_mesh_compression.prototype.dispose = function () {
  93405. if (this._dracoCompression) {
  93406. this._dracoCompression.dispose();
  93407. }
  93408. _super.prototype.dispose.call(this);
  93409. };
  93410. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93411. var _this = this;
  93412. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  93413. if (primitive.mode != undefined) {
  93414. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  93415. primitive.mode !== 4 /* TRIANGLES */) {
  93416. throw new Error(context + ": Unsupported mode " + primitive.mode);
  93417. }
  93418. // TODO: handle triangle strips
  93419. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  93420. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  93421. }
  93422. }
  93423. var attributes = {};
  93424. var loadAttribute = function (name, kind) {
  93425. var uniqueId = extension.attributes[name];
  93426. if (uniqueId == undefined) {
  93427. return;
  93428. }
  93429. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93430. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93431. babylonMesh._delayInfo.push(kind);
  93432. }
  93433. attributes[kind] = uniqueId;
  93434. };
  93435. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93436. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93437. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93438. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93439. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93440. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93441. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93442. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93443. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  93444. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  93445. try {
  93446. if (!_this._dracoCompression) {
  93447. _this._dracoCompression = new BABYLON.DracoCompression();
  93448. }
  93449. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  93450. }
  93451. catch (e) {
  93452. throw new Error(context + ": " + e.message);
  93453. }
  93454. });
  93455. });
  93456. };
  93457. return KHR_draco_mesh_compression;
  93458. }(GLTF2.GLTFLoaderExtension));
  93459. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  93460. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  93461. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93462. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93463. })(BABYLON || (BABYLON = {}));
  93464. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  93465. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93466. var BABYLON;
  93467. (function (BABYLON) {
  93468. var GLTF2;
  93469. (function (GLTF2) {
  93470. var Extensions;
  93471. (function (Extensions) {
  93472. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  93473. var NAME = "KHR_materials_pbrSpecularGlossiness";
  93474. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  93475. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  93476. function KHR_materials_pbrSpecularGlossiness() {
  93477. var _this = _super !== null && _super.apply(this, arguments) || this;
  93478. _this.name = NAME;
  93479. return _this;
  93480. }
  93481. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93482. var _this = this;
  93483. return this._loadExtensionAsync(context, material, function (context, extension) {
  93484. material._babylonMeshes = material._babylonMeshes || [];
  93485. material._babylonMeshes.push(babylonMesh);
  93486. if (material._loaded) {
  93487. babylonMesh.material = material._babylonMaterial;
  93488. return material._loaded;
  93489. }
  93490. var promises = new Array();
  93491. var babylonMaterial = _this._loader._createMaterial(material);
  93492. material._babylonMaterial = babylonMaterial;
  93493. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  93494. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  93495. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93496. babylonMesh.material = babylonMaterial;
  93497. return (material._loaded = Promise.all(promises).then(function () { }));
  93498. });
  93499. };
  93500. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  93501. var promises = new Array();
  93502. var babylonMaterial = material._babylonMaterial;
  93503. if (properties.diffuseFactor) {
  93504. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  93505. babylonMaterial.alpha = properties.diffuseFactor[3];
  93506. }
  93507. else {
  93508. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93509. }
  93510. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  93511. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  93512. if (properties.diffuseTexture) {
  93513. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  93514. babylonMaterial.albedoTexture = texture;
  93515. }));
  93516. }
  93517. if (properties.specularGlossinessTexture) {
  93518. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  93519. babylonMaterial.reflectivityTexture = texture;
  93520. }));
  93521. babylonMaterial.reflectivityTexture.hasAlpha = true;
  93522. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  93523. }
  93524. loader._loadMaterialAlphaProperties(context, material);
  93525. return Promise.all(promises).then(function () { });
  93526. };
  93527. return KHR_materials_pbrSpecularGlossiness;
  93528. }(GLTF2.GLTFLoaderExtension));
  93529. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  93530. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  93531. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93532. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93533. })(BABYLON || (BABYLON = {}));
  93534. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  93535. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93536. var BABYLON;
  93537. (function (BABYLON) {
  93538. var GLTF2;
  93539. (function (GLTF2) {
  93540. var Extensions;
  93541. (function (Extensions) {
  93542. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  93543. var NAME = "KHR_lights";
  93544. var LightType;
  93545. (function (LightType) {
  93546. LightType["AMBIENT"] = "ambient";
  93547. LightType["DIRECTIONAL"] = "directional";
  93548. LightType["POINT"] = "point";
  93549. LightType["SPOT"] = "spot";
  93550. })(LightType || (LightType = {}));
  93551. var KHR_lights = /** @class */ (function (_super) {
  93552. __extends(KHR_lights, _super);
  93553. function KHR_lights() {
  93554. var _this = _super !== null && _super.apply(this, arguments) || this;
  93555. _this.name = NAME;
  93556. return _this;
  93557. }
  93558. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  93559. var _this = this;
  93560. return this._loadExtensionAsync(context, scene, function (context, extension) {
  93561. var promise = _this._loader._loadSceneAsync(context, scene);
  93562. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93563. if (light.type !== LightType.AMBIENT) {
  93564. throw new Error(context + ": Only ambient lights are allowed on a scene");
  93565. }
  93566. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  93567. return promise;
  93568. });
  93569. };
  93570. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  93571. var _this = this;
  93572. return this._loadExtensionAsync(context, node, function (context, extension) {
  93573. var promise = _this._loader._loadNodeAsync(context, node);
  93574. var babylonLight;
  93575. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93576. var name = node._babylonMesh.name;
  93577. switch (light.type) {
  93578. case LightType.AMBIENT: {
  93579. throw new Error(context + ": Ambient lights are not allowed on a node");
  93580. }
  93581. case LightType.DIRECTIONAL: {
  93582. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  93583. break;
  93584. }
  93585. case LightType.POINT: {
  93586. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  93587. break;
  93588. }
  93589. case LightType.SPOT: {
  93590. var spotLight = light;
  93591. // TODO: support inner and outer cone angles
  93592. //const innerConeAngle = spotLight.innerConeAngle || 0;
  93593. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  93594. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  93595. break;
  93596. }
  93597. default: {
  93598. throw new Error(context + ": Invalid light type " + light.type);
  93599. }
  93600. }
  93601. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  93602. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  93603. babylonLight.parent = node._babylonMesh;
  93604. return promise;
  93605. });
  93606. };
  93607. Object.defineProperty(KHR_lights.prototype, "_lights", {
  93608. get: function () {
  93609. var extensions = this._loader._gltf.extensions;
  93610. if (!extensions || !extensions[this.name]) {
  93611. throw new Error("#/extensions: " + this.name + " not found");
  93612. }
  93613. var extension = extensions[this.name];
  93614. return extension.lights;
  93615. },
  93616. enumerable: true,
  93617. configurable: true
  93618. });
  93619. return KHR_lights;
  93620. }(GLTF2.GLTFLoaderExtension));
  93621. Extensions.KHR_lights = KHR_lights;
  93622. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  93623. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93624. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93625. })(BABYLON || (BABYLON = {}));
  93626. //# sourceMappingURL=KHR_lights.js.map
  93627. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  93628. globalObject["BABYLON"] = BABYLON;
  93629. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;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 DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  93630. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,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,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };